【问题标题】:Azure AD B2C - Role management [duplicate]Azure AD B2C - 角色管理
【发布时间】:2018-02-03 18:19:22
【问题描述】:

我有一个与 Azure AD B2C 连接的 Asp.NET MVC 应用程序。

在管理员设置中我创建了一个管理员组:

在我的代码中我想使用[Authorize(Roles = "Administrator")]

使用常规 Azure Active Directory 很容易添加(只需 3 行代码)。但是对于 Azure AD B2C,我在网络上找不到任何有效的教程或示例。也许你可以告诉我我需要修改什么。

这是我的 Startup.Auth.cs 的 ConfigureAuth 方法

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

    app.UseCookieAuthentication(new CookieAuthenticationOptions());

    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            // Generate the metadata address using the tenant and policy information
            MetadataAddress = String.Format(AadInstance, Tenant, DefaultPolicy),

            // These are standard OpenID Connect parameters, with values pulled from web.config
            ClientId = ClientId,
            RedirectUri = RedirectUri,
            PostLogoutRedirectUri = RedirectUri,

            // Specify the callbacks for each type of notifications
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                RedirectToIdentityProvider = OnRedirectToIdentityProvider,
                AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                AuthenticationFailed = OnAuthenticationFailed,
            },

            // Specify the claims to validate
            TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = "name"
            },

            // Specify the scope by appending all of the scopes requested into one string (separated by a blank space)
            Scope = $"openid profile offline_access {ReadTasksScope} {WriteTasksScope}"
        }
    );
}

【问题讨论】:

    标签: c# asp.net-mvc azure asp.net-mvc-5 azure-ad-b2c


    【解决方案1】:

    Azure AD B2C 尚未在其发送到应用程序的令牌中包含组声明,因此您无法采用与 Azure AD 概述的相同方法(其中确实包含组声明令牌)。

    您可以在 Azure AD B2C 反馈论坛中投票支持此功能:Get user membership groups in the claims with Azure AD B2C

    话虽如此,您可以在此应用程序中做一些额外的工作,让它手动检索组声明的这些声明并将它们注入到令牌中

    首先,注册一个单独的应用程序,该应用程序将调用 Microsoft Graph 来检索组声明

    1. 转到https://apps.dev.microsoft.com
    2. 使用应用程序权限创建一个应用程序:Directory.Read.All
    3. 通过单击生成新密码添加应用程序密码
    4. 添加平台并选择 Web 并为其提供任何重定向 URI(例如 https://yourtenant.onmicrosoft.com/groups
    5. 导航至:https://login.microsoftonline.com/YOUR_TENANT.onmicrosoft.com/adminconsent?client_id=YOUR_CLIENT_ID&state=12345&redirect_uri=YOUR_REDIRECT_URI 同意此应用程序

    然后,您将需要在OnAuthorizationCodeReceived 处理程序中添加以下代码right after redeeming the code

    var authority = $"https://login.microsoftonline.com/{Tenant}";
    var graphCca = new ConfidentialClientApplication(GraphClientId, authority, GraphRedirectUri, new ClientCredential(GraphClientSecret), userTokenCache, null);
    string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
    
    try
    {
        AuthenticationResult authenticationResult = await graphCca.AcquireTokenForClientAsync(scopes);
        string token = authenticationResult.AccessToken;
    
        using (var client = new HttpClient())
        {
            string requestUrl = $"https://graph.microsoft.com/v1.0/users/{signedInUserID}/memberOf?$select=displayName";
    
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
    
            HttpResponseMessage response = await client.SendAsync(request);
            var responseString = await response.Content.ReadAsStringAsync();
    
            var json = JObject.Parse(responseString);
    
            foreach (var group in json["value"])
                notification.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role, group["displayName"].ToString(), System.Security.Claims.ClaimValueTypes.String, "Graph"));
    
            //TODO: Handle paging. 
            // https://developer.microsoft.com/en-us/graph/docs/concepts/paging
            // If the user is a member of more than 100 groups, 
            // you'll need to retrieve the next page of results.
        }
    } catch (Exception ex)
    {
        //TODO: Handle
        throw;
    }
    

    【讨论】:

    • 首先非常感谢您的回答!我只剩下两个问题了。我应该在哪里添加该 URL(第 4 步)以及重定向 uri 是什么(这是 b2c 的回复 uri 吗?)?代码的另一个问题:我应该填写哪些变量:- GraphClientId - GraphRedirectUri - GraphClientSecret - userTokenCache 并且 VisualStudio 正在调用错误消息:新 c.Claim 非常感谢您的帮助 :-)
    • 进行了更新以进一步阐明应用注册说明并解决 c.Claim 问题。
    • GraphClientID = 您注册的应用程序的应用程序 ID,GraphSecret = 应用程序密钥,GraphRedirectUri = 您指定的重定向 URI,userTokenCache 应该已经从示例中的 OnAuthorizationCodeReceived 代码中定义。
    • 终于让它工作 - 如果其他人需要答案:重定向 URI 与 azure 门户中的相同。在链接中,您需要将“common”更改为您的 b2c 租户 ID。再次感谢您的帮助萨卡
    • 您没有修改实际的令牌。您正在向令牌的 .Net 抽象添加声明,该令牌在验证令牌后在内存中生成。
    猜你喜欢
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    相关资源
    最近更新 更多