繁体   English   中英

MVC5 应用程序中来自 Azure ADB2C 的 AccessToken

[英]AccessToken from Azure ADB2C in MVC5 application

我们正在开发一个 MVC5 Web 应用程序,它使用 OpenIdConnect 对 Azure AD B2C 进行身份验证。 当用户通过身份验证后,我们希望能够从 Azure AD B2C 获取访问令牌,以便使用我们的 API。

这是我们的 Startup.cs 等效代码:

protected override void ProcessCore(IdentityProvidersArgs args)
{
    Assert.ArgumentNotNull(args, nameof(args));

    List<B2CConfig> ssoSettings = _ssoConfigurationRepository.GetAllSettings();

    foreach (var config in ssoSettings)
    {
        args.App.UseOpenIdConnectAuthentication(CreateOptionsFromSiteConfig(config));
    }
}

private OpenIdConnectAuthenticationOptions CreateOptionsFromSiteConfig(B2CConfig config)
{
    OpenIdConnectAuthenticationOptions options = new OpenIdConnectAuthenticationOptions();
    options.MetadataAddress = string.Format(_aadInstance, _tenant, config.Policy);
    options.AuthenticationType = config.Policy;
    options.AuthenticationMode = AuthenticationMode.Passive;
    options.RedirectUri = config.AzureReplyUri;
    options.PostLogoutRedirectUri = config.LogoutRedirectUri;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType = "emails"
    };

    var identityProvider = GetIdentityProvider();

    options.Notifications = new OpenIdConnectAuthenticationNotifications()
    {
        AuthenticationFailed = AuthenticationFailed,
        RedirectToIdentityProvider = notification =>
        {
            return Task.FromResult(notification.ProtocolMessage.UiLocales = config.UiLocale ?? string.Empty);
        },
        SecurityTokenValidated = notification =>
        {
            notification.AuthenticationTicket.Identity.AddClaim(new Claim("idp", "azureadb2c"));

            // transform all claims
            ClaimsIdentity identity = notification.AuthenticationTicket.Identity;
            notification.AuthenticationTicket.Identity.ApplyClaimsTransformations(new TransformationContext(FederatedAuthenticationConfiguration, identityProvider));

            return Task.CompletedTask;
        }
    };

    options.ClientId = config.ClientId;
    options.Scope = "openid";
    options.ResponseType = "id_token";

    return options;
}

private Task AuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
    notification.HandleResponse();

    // Handle the error code that Azure AD B2C throws when trying to reset a password from the login page
    // because password reset is not supported by a "sign-up or sign-in policy"
    if (notification.ProtocolMessage.ErrorDescription != null && notification.ProtocolMessage.ErrorDescription.Contains("AADB2C90118"))
    {
        SsoLogger.Warn("User triggered reset password");
        notification.Response.Redirect(SsoConfiguration.Routes.ResetPassword);
    }
    else if (notification.Exception.Message == "access_denied")
    {
        notification.Response.Redirect("/");
    }
    else
    {
        SsoLogger.Warn("AuthenticationFailed", notification.Exception);
        notification.Response.Redirect(SsoConfiguration.Routes.LoginError);
    }

    return Task.FromResult(0);
}

在 Asp.Net 核心中,您似乎会在 HttpContext 上调用GetTokenAsync ,但该扩展方法在 .NET 4.72 中不可用。

任何人都可以帮助弄清楚如何从 AzureAD B2C 检索可用于调用我们的 WebApi 的访问令牌? 或者我可以只存储从 SecurityTokenValidated 事件中获得的访问令牌并将其用于所有 API 请求?

这是一个可能的解决方案: 将 access_token 存储在用户声明中以获得授权是否安全?

Notifications = new OpenIdConnectAuthenticationNotifications
{
    SecurityTokenValidated = notification =>
    {
        var identity = notification.AuthenticationTicket.Identity;
        identity.AddClaim(claim: new Claim(type: "auth_token", value: 
           notification.ProtocolMessage.AccessToken));
        return Task.CompletedTask;
    }
}

如果有人有更好的方法,我会很乐意接受另一个答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM