求ASP.NET Core Identity结合ITfoxtec.Identity.Saml2多IDP集成示例
ITfoxtec.Identity.Saml2 与 ASP.NET Core Identity 多身份提供商集成示例
核心扩展方法实现
你提供的AddSaml扩展方法可用于快速注册多个SAML身份提供商,完整实现示例如下:
public static class Saml2Extensions { public static AuthenticationBuilder AddSaml(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<Saml2Options> configureOptions) { // 注册SAML2身份验证方案与处理程序 builder.AddScheme<Saml2Options, Saml2Handler>(authenticationScheme, displayName, configureOptions); // 添加SAML2相关依赖服务 builder.Services.AddSaml2(); return builder; } }
多身份提供商混合集成配置
在Program.cs(或Startup.cs)中,可同时配置多个SAML身份提供商与OIDC类型的Google、Azure身份提供商,实现混合登录场景:
var builder = WebApplication.CreateBuilder(args); // 初始化ASP.NET Core Identity服务 builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>(); // 配置多身份提供商 builder.Services.AddAuthentication() // Stub SAML身份提供商 .AddSaml("StubSaml", "Stub SAML IDP", options => { options.SignInScheme = IdentityConstants.ExternalScheme; options.EntityId = new EntityId("https://你的应用域名/saml2"); options.SingleSignOnDestination = new Uri("https://stubidp.sustainsys.com/Idp/SSOService.aspx"); options.SingleLogoutDestination = new Uri("https://stubidp.sustainsys.com/Idp/SLOService.aspx"); options.IdentityProviderSigningKeys.AddConfiguredKey(new X509Certificate2("StubIdpCert.cer")); }) // Okta SAML身份提供商 .AddSaml("OktaSaml", "Okta", options => { options.SignInScheme = IdentityConstants.ExternalScheme; options.EntityId = new EntityId("https://你的应用域名/saml2"); options.SingleSignOnDestination = new Uri("https://你的Okta域名/app/应用ID/sso/saml"); options.SingleLogoutDestination = new Uri("https://你的Okta域名/app/应用ID/slo/saml"); options.IdentityProviderSigningKeys.AddConfiguredKey(new X509Certificate2("OktaCert.cer")); }) // Google OIDC登录 .AddGoogle("Google", options => { options.ClientId = builder.Configuration["Authentication:Google:ClientId"]; options.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"]; options.SignInScheme = IdentityConstants.ExternalScheme; }) // Azure AD OIDC登录 .AddMicrosoftAccount("AzureAD", options => { options.ClientId = builder.Configuration["Authentication:AzureAD:ClientId"]; options.ClientSecret = builder.Configuration["Authentication:AzureAD:ClientSecret"]; options.SignInScheme = IdentityConstants.ExternalScheme; }); var app = builder.Build(); // 中间件配置 app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapRazorPages(); app.Run();
多IDP登录页效果
配置完成后,登录页可展示所有已配置的身份提供商选项,效果如下:

关键注意事项
- 每个SAML身份提供商需配置唯一的
authenticationScheme和displayName,用于区分不同登录入口 - 所有身份提供商的
SignInScheme需设置为IdentityConstants.ExternalScheme,确保与ASP.NET Core Identity的外部登录流程兼容 - 需根据各SAML身份提供商的要求,正确配置单点登录/登出地址、签名证书等核心参数
内容的提问来源于stack exchange,提问作者Herb Stahl
相关产品推荐
相关产品推荐

