Azure SSO Active Directory с MSAL и openID Connect - PullRequest
0 голосов
/ 09 июля 2020

Мне было поручено написать веб-сайт ASP. NET, который использует Azure Active Directory. Я пошел по маршруту OAuth и OpenID Connect. Я не могу использовать неявный поток и поэтому должен установить ResponseType как код. Используя образцы кода MSAL, я получил большую часть его работ, но проблема в том, что все образцы используют тип ответа, который возвращает токены. Я думаю, мне нужно сделать это в два отдельных шага, сначала получить код авторизации, а затем получить токен идентификатора. Я не совсем уверен, как это сделать, и был бы очень признателен за некоторые рекомендации здесь.

У меня есть класс запуска, который выглядит следующим образом:

 public void Configuration(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions { });

        app.UseOpenIdConnectAuthentication(
             new OpenIdConnectAuthenticationOptions
             {
                 Authority = authority,
                 ClientId = clientId,
                 RedirectUri = redirectUri,
                 Scope = "openid profile email offline_access user.readbasic.all", // a basic set of permissions for user sign in & profile access
                 ResponseType = OpenIdConnectResponseType.Code,
                 ClientSecret = clientSecret,
                 TokenValidationParameters = new TokenValidationParameters
                 {
                     // In a real application you would use ValidateIssuer = true for additional checks and security.
                     ValidateIssuer = false,
                     NameClaimType = "name",
                 },
                 Notifications = new OpenIdConnectAuthenticationNotifications()
                 {
                     AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                     AuthenticationFailed = OnAuthenticationFailed,
                 }
             }); 
    }
    private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
    {
        // Handle any unexpected errors during sign in
        context.OwinContext.Response.Redirect("/Error?message=" + context.Exception.Message);
        context.HandleResponse(); // Suppress the exception
        return Task.FromResult(0);
    }

    private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
    {
        /*
         The `MSALPerUserMemoryTokenCache` is created and hooked in the `UserTokenCache` used by `IConfidentialClientApplication`.
         At this point, if you inspect `ClaimsPrinciple.Current` you will notice that the Identity is still unauthenticated and it has no claims,
         but `MSALPerUserMemoryTokenCache` needs the claims to work properly. Because of this sync problem, we are using the constructor that
         receives `ClaimsPrincipal` as argument and we are getting the claims from the object `AuthorizationCodeReceivedNotification context`.
         This object contains the property `AuthenticationTicket.Identity`, which is a `ClaimsIdentity`, created from the token received from 
         Azure AD and has a full set of claims.
         */
        IConfidentialClientApplication confidentialClient = GroupManager.Utils.MsalAppBuilder.BuildConfidentialClientApplication(null);

        // Upon successful sign in, get & cache a token using MSAL
        AuthenticationResult result = await confidentialClient.AcquireTokenByAuthorizationCode(new[] { "openid profile email offline_access user.readbasic.all" }, context.Code).ExecuteAsync();       
        
    }

Как мне получить информацию из токены результата и создать удостоверение утверждения для AuthenticationTicket.Identity и получить доступ к информации о пользователе?

Обратите внимание, что это приложение ASP. NET. Не MVC и не Core.

1 Ответ

0 голосов
/ 10 июля 2020

Если вы используете MSAL, вам не нужно самостоятельно обрабатывать code. MSAL вернет вам токен после того, как вы войдете в систему в интерактивном режиме, см.: Обзор библиотеки аутентификации Microsoft (MSAL) .

Перед этим вам нужно взглянуть на Добавьте вход в Microsoft в веб-приложение ASP. NET , рабочий процесс: enter image description here

Code example please check: https://github.com/AzureAdQuickstarts/AppModelv2-WebApp-OpenIDConnect-DotNet

Обновление:

Попробуйте включить идентификационный токен

введите описание изображения здесь

...