Azure AD B2C - 角色管理

28

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

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

enter image description here

在我的代码中,我想使用[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}"
        }
    );
}
1个回答

28

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. 创建具有Application Permissions:Directory.Read.All的应用程序。
  3. 点击Generate new password添加应用程序秘密。
  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处理程序内添加以下代码,在兑换代码之后

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 在new c.Claim处报错。非常感谢您的帮助 :-)
- DarkWing89
已更新以进一步澄清应用程序注册说明并解决c.Claim问题。 - Saca
1
GraphClientID = 您注册的应用程序的应用程序 ID, GraphSecret = 应用程序密钥, GraphRedirectUri = 您指定的重定向 URI, userTokenCache 应该已经从示例中的 OnAuthorizationCodeReceived 代码中定义。 - Saca
1
终于搞定了 - 如果其他人需要答案:重定向URI与Azure门户中的相同。在链接中,您需要将“common”更改为您的B2C租户ID。再次感谢您的帮助Saca。 - DarkWing89
2
您并未修改实际的令牌。在验证令牌后,您正在向 .Net 抽象中添加声明,该抽象是在内存中生成的。 - Saca
显示剩余7条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接