Search code examples
oauth-2.0azure-ad-b2cazure-authentication

Cannot get role from logged-in Azure AD B2C user


I am attempting to use the following to determine if an Azure AD B2C logged-in user is an Administrator:

if (User.IsInRole("Administrator")) 
{
    .... Display special info for Admins ....
}

However, when I look into the System.Security.Principal.IPrincipal.User object, I see null for the list of roles that this user has:

enter image description here

The following is the relevant code that configures authentication and requests TokenValidationParameters, including for the roles to be validated. I've tried the following: RoleClaimType = "role" and RoleClaimType = "roles", both of which haven't worked for me.

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

        app.UseKentorOwinCookieSaver();

        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            CookieSecure = CookieSecureOption.Always
        });

        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,
                Authority = Authority,
                PostLogoutRedirectUri = RedirectUri,
                RedirectUri = RedirectUri,

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    RedirectToIdentityProvider = OnRedirectToIdentityProvider,
                    AuthenticationFailed = OnAuthenticationFailed,
                    AuthorizationCodeReceived = OnAuthorizationCodeReceived
                },

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

                // Specify the scope by appending all of the scopes requested into one string (seperated by a blank space)
                Scope = $"{OpenIdConnectScopes.OpenId} {ReadTasksScope} {WriteTasksScope}"
            }
        );
    }

However, when I decode the id_token retrieved from the authentication process and decode it using the tool https://jwt.ms/, I don't see a "roles" claim, as shown in the screenshot.

enter image description here

Furthermore, in the SignIn Azure AD B2C policy, perhaps I need to add a "roles" ClaimType?

enter image description here

Please help! What else do I need to do in order to get User.IsInRole("Administrator") to work? Thank you!


Solution

  • To solve this, I ended up using the Azure AD Graph Client to query for all of the directory roles belonging to a user with a specified objectId. Here is the method I added:

        public async Task<string> GetUserRoleByObjectId(string objectId)
        {
            return await SendGraphGetRequest("/users/" + objectId + "/$links/memberOf", null);
        }
    

    I added this method to the B2CGraphClient.cs file in the following sample code, which I integrated into my web app: https://github.com/AzureADQuickStarts/B2C-GraphAPI-DotNet