【问题标题】:Azure Active Directory SSO with MSAL and openID Connect带有 MSAL 和 openID Connect 的 Azure Active Directory SSO
【发布时间】:2020-10-30 06:45:18
【问题描述】:

我的任务是编写一个使用 Azure Active Directory 的 ASP.NET 网站。我选择了 OAuth 和 OpenID Connect 的路线。我无法使用隐式流,因此必须将 ResponseType 设置为代码。 使用 MSAL 代码示例,我得到了大部分工作,但问题是所有示例都使用返回令牌的响应类型。我想我需要分两个步骤来完成,首先获取授权码,然后获取 id 令牌。我不确定如何执行此操作,非常感谢这里的一些指导。

我有一个如下所示的启动类:

 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。

【问题讨论】:

    标签: asp.net oauth-2.0 azure-active-directory single-sign-on openid-connect


    【解决方案1】:

    如果您使用 MSAL,则无需自己处理 code。 MSAL会在您交互登录后将token返还给您,请查看:Overview of Microsoft Authentication Library (MSAL)

    在这之前,你需要看看Add sign-in to Microsoft to an ASP.NET web app,工作流程是:

    代码示例请查看:https://github.com/AzureAdQuickstarts/AppModelv2-WebApp-OpenIDConnect-DotNet

    更新:

    尝试启用 ID 令牌

    【讨论】:

    • 所有这些示例在 OpenIdConnectAuthenticationOptions 中都有 ResponseType = OpenIdConnectResponseType.IdToken。这给了我错误:'unsupported_response_type'。 Error_Description(可能为空):'AADSTS700054: response_type 'id_token' 未为应用程序启用。
    • @Dassy 尝试启用 ID 令牌。这会将属性 oauth2AllowIdTokenImplicitFlow 添加到清单文件中,并将值设置为“true”。
    • 感谢您的 cmets。就像我在问题中所说的,出于安全原因,我的 IT 公司对使用隐式流犹豫不决。因此,他们专门将其关闭。我需要帮助尽快解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 2019-05-07
    • 2021-10-15
    • 2017-06-21
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 2017-09-08
    相关资源
    最近更新 更多