如何在 Azure 活动目录中使用多个 OpenIdConnectAuthenticationOptions

How to use multiple OpenIdConnectAuthenticationOptions in Azure active directory

在我们的项目中,我们想要显示两个选项(以员工身份登录和以客户身份登录)。根据选择,我们希望使用 Azure Active Directory B2B 或 Azure B2C 对用户进行身份验证。

我可以将身份验证模式设置为被动并在单击 link 后打开登录页面。它在配置单个 OpenIdConnectAuthenticationOptions 时运行良好。但是当我配置多个 OpenIdConnectAuthenticationOptions 时,这不起作用。

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Passive,
                MetadataAddress = String.Format(aadInstance2, tenant2, SignUpSignInPolicyId),
                ClientId = clientId2,
                RedirectUri = redirectUri2,
                PostLogoutRedirectUri = postLogoutRedirectUri,
            });

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Passive,
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
            });

    public void Redirect()
    {
       HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "https://localhost/WebApp1/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
    }

您可以尝试使用 AuthenticationType 。此 属性 在管道中标识此中间件,并用于在身份验证操作中引用它。例如,您可以定义这样的配置:

app.UseOpenIdConnectAuthentication(
    new OpenIdConnectAuthenticationOptions("AADLogin")
    {
        AuthenticationMode = AuthenticationMode.Passive,
        MetadataAddress = String.Format(aadInstance2, tenant2, SignUpSignInPolicyId),
        ClientId = clientId2,
        RedirectUri = redirectUri2,
        PostLogoutRedirectUri = postLogoutRedirectUri,
    });

app.UseOpenIdConnectAuthentication(
    new OpenIdConnectAuthenticationOptions("B2CLogin")
    {
        AuthenticationMode = AuthenticationMode.Passive,
        ClientId = clientId,
        Authority = authority,
        PostLogoutRedirectUri = postLogoutRedirectUri,
    });

然后取决于用户的选择,您可以选择使用哪一个:

    if ()
    {
        HttpContext.GetOwinContext()
            .Authentication.Challenge(new AuthenticationProperties {RedirectUri = "/"},
               "AADLogin");
    }
    else
    {
        HttpContext.GetOwinContext()
           .Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" },
              "B2CLogin");
    }