HowTo: ADB2C User Groups in Token

时间:2019-04-08 12:53:06

标签: azure-ad-b2c claims

I am running a ADB2C tenant and would like to know how to configure and retrieve user groups within a auth token in the ADB2C auth flow.

I am able to configure and receive the custom attribute in my token but I am unable to configure groups claim that can potentially list user membership to a certain group(s).

expected is a groups:{}

1 个答案:

答案 0 :(得分:0)

在B2C中,没有将在令牌中返回的组声明,因此您无法在Azure AD中遵循相同的方法。

您可以尝试让应用程序手动检索组声明中的这些声明并将它们注入令牌中。

通过这种方式,您可以参考Azure AD中的方法:

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;
}