以下是一个使用ASP.NET Core进行LDAP Active Directory身份验证的示例代码:
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace YourProjectNamespace
{
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.Authority = "https://your-ldap-server-url";
options.ClientId = "your-client-id";
options.ResponseType = "code";
options.CallbackPath = "/signin-oidc";
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.UsePkce = false;
options.SaveTokens = true;
options.TokenValidationParameters.ValidateIssuer = false;
options.TokenValidationParameters.NameClaimType = "preferred_username";
});
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseAuthentication();
app.UseAuthorization();
// ...
}
}
}
using Microsoft.AspNetCore.Mvc;
namespace YourProjectNamespace.Controllers
{
public class HomeController : Controller
{
[Authorize]
public IActionResult Index()
{
// 这个操作需要认证
return View();
}
// ...
}
}
@using Microsoft.AspNetCore.Authentication
@if (User.Identity.IsAuthenticated)
{
Welcome, @User.Identity.Name!
}
else
{
Anonymous
Login
}
这是一个基本的示例,您可以根据自己的需求进行自定义和扩展。