要使用两个AD进行身份验证,我们需要为每个AD设置单独的配置。以下是一个简单的示例:
public class CustomAuthOptions
{
public string Ldap1ConnectionString { get; set; }
public string Ldap2ConnectionString { get; set; }
public string Ldap1SearchBase { get; set; }
public string Ldap2SearchBase { get; set; }
}
public void ConfigureServices(IServiceCollection services)
{
// 添加身份验证选项
services.Configure(Configuration.GetSection("CustomAuth"));
// 添加认证服务
services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
// 添加第一个认证方案
.AddJwtBearer("Ldap1", options =>
{
var ldap1Options = Configuration.GetSection("CustomAuth").Get();
options.Authority = ldap1Options.Ldap1ConnectionString;
options.RequireHttpsMetadata = false;
options.Audience = "api1";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("SuperSecretKey")),
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = "api1",
ValidIssuer = ldap1Options.Ldap1SearchBase
};
})
// 添加第二个认证方案
.AddJwtBearer("Ldap2", options =>
{
var ldap2Options = Configuration.GetSection("CustomAuth").Get();
options.Authority = ldap2Options.Ldap2ConnectionString;
options.RequireHttpsMetadata = false;
options.Audience = "api2";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey