我可以在 运行 时使用 OWIN 和 OpenID 更改身份提供者吗?

Can I change Identity Providers with OWIN and OpenID at run time?

我正在使用 OWIN 中间件来配置 OpenID 身份验证。此配置在指向 B2C IDP 的 StartUp.cs 处调用。

public void ConfigureAuth(IAppBuilder app)
{
    // Required for Azure webapps, as by default they force TLS 1.2 and this project attempts 1.0
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        // ASP.NET web host compatible cookie manager
        CookieManager = new SystemWebChunkingCookieManager()
    });

    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            // Generate the metadata address using the tenant and policy information
            MetadataAddress = String.Format(Globals.WellKnownMetadata, Globals.Tenant, Globals.DefaultPolicy),

            // These are standard OpenID Connect parameters, with values pulled from web.config
            ClientId = Globals.ClientId,
            RedirectUri = Globals.RedirectUri,
            PostLogoutRedirectUri = Globals.RedirectUri,

            // Specify the callbacks for each type of notifications
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                RedirectToIdentityProvider = OnRedirectToIdentityProvider,
                AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                AuthenticationFailed = OnAuthenticationFailed,
            },

            // Specify the claim type that specifies the Name property.
            TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = "name",
                ValidateIssuer = false
            },

            // Specify the scope by appending all of the scopes requested into one string (separated by a blank space)
            Scope = $"openid profile offline_access {Globals.ReadTasksScope} {Globals.WriteTasksScope}",

            // ASP.NET web host compatible cookie manager
            CookieManager = new SystemWebCookieManager()
        }
    );
}

如何让中间件使用不同的配置,特别是针对对象 OpenIdConnectAuthenticationOptions,以便在运行时指向不同的 IDP?

您可以注册多个命名的 openIDCConnect 处理程序,例如

.AddOpenIdConnect("Auth0", options =>
{  Options...
}
.AddOpenIdConnect("google", options =>
{  Options...
}
.AddOpenIdConnect("facebook", options =>
{  Options...
}

然后用户可以选择他想要的身份验证方式,使用以下之一:

HttpContext.SignInAsync("Auth0",....);
HttpContext.SignInAsync("google",....);
HttpContext.SignInAsync("facebook",....);
    

当您添加多个处理程序时,您需要确保客户端中的本地回调路径对于每个处理程序都是不同的,例如

CallbackPath = new PathString("/signin-auth0");
CallbackPath = new PathString("/signin-google");
CallbackPath = new PathString("/signin-facebook");

(您在选项中设置)