AccessToken из Azure ADB2 C в приложении MVC5 - PullRequest
0 голосов
/ 10 января 2020

Мы работаем над веб-приложением MVC5, которое использует OpenIdConnect для аутентификации в Azure AD B2 C. Когда пользователь прошел аутентификацию, мы хотели бы иметь возможность получить маркеры доступа у Azure AD B2 C, чтобы использовать их в нашем 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 кажется, что вы вызовете GetTokenAsync для HttpContext, но этот метод расширения недоступен в. NET 4.72.

Может Кто-нибудь помочь выяснить, как получить токен доступа из AzureAD B2 C, который может быть использован в вызовах нашего WebApi? Или я могу просто сохранить токен доступа, полученный из события SecurityTokenValidated, и использовать его для всех запросов API?

1 Ответ

0 голосов
/ 10 января 2020

Это возможное решение: Безопасно ли хранить 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;
    }
}

Если у кого-то есть лучший подход, я с радостью приму другой ответ .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...