Azure AD B2C 尚未在发送到应用程序的令牌中包含组声明因此,您不能遵循与 Azure AD 概述相同的方法(它在令牌中包含组声明)。
您可以通过在 Azure AD B2C 反馈论坛中投票来支持此功能:使用 Azure AD B2C 获取声明中的用户成员身份组
话虽如此,您可以在此应用程序中执行一些额外的工作,以使其手动检索组声明的这些声明并将其注入令牌中.
First, 注册一个单独的应用程序,该应用程序将调用 Microsoft Graph 来检索组声明.
- Go to https://apps.dev.microsoft.com
- 创建一个应用程序应用程序权限 : 目录.读取.全部.
- 单击添加应用程序机密生成新密码
- 添加平台并选择 Web 并为其提供任何重定向 URI(例如
https://yourtenant.onmicrosoft.com/groups
)
- 通过导航至同意此应用程序:
https://login.microsoftonline.com/YOUR_TENANT.onmicrosoft.com/adminconsent?client_id=YOUR_CLIENT_ID&state=12345&redirect_uri=YOUR_REDIRECT_URI
然后,你会需要添加代码如下代码里面OnAuthorizationCodeReceived
handler, 兑换代码后立即:
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;
}