能否给出一个C# .NET Core中实现Active Directory验证的具体代码示例?
时间: 2024-10-25 18:11:44 浏览: 11
【ASP.NET编程知识】ASP.NET中实现弹出日历示例.docx
在.NET Core中,你可以使用`Microsoft.AspNetCore.Authentication.ActiveDirectory`库来实现Active Directory验证。这里是一个简单的代码示例,展示了如何配置和服务提供器:
首先,你需要添加依赖项:
```json
{
"dependencies": {
"Microsoft.AspNetCore.Authentication.ActiveDirectory": "6.0.0",
"Microsoft.AspNetCore.Authentication.OpenIdConnect": "6.0.0"
}
}
```
然后,在Startup.cs中配置认证:
```csharp
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Httpoverrides;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
public void ConfigureServices(IServiceCollection services)
{
// 添加Active Directory认证服务
services.AddAuthentication(AdDefaults.AuthenticationScheme)
.AddAzureADBearer(options =>
{
options.Authority = "<your-AD-authority-url>";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = options.Authority,
ValidateAudience = true,
ValidAudience = "<your-app-id-or-client-id>",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("<your-client-secret>")),
RequireExpirationTime = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseAuthentication(); // 首先启用身份验证
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireAuthorization();
});
}
```
在这个例子中,你需要替换`<your-AD-authority-url>`、`<your-app-id-or-client-id>` 和 `<your-client-secret>`为你的实际AD设置。
当用户访问受保护的资源时,他们会被引导到AD的登录页面。一旦他们成功登录,系统会检查提供的token是否有效。若验证通过,用户就获得了访问权限。
阅读全文