B2C application unable to retrieve roles assigned to a user

AKJ 20 Reputation points
2023-06-08T17:51:58.48+00:00

Hello, In my B2C app, I have a user that has been assigned multiple administrative roles. I've created a policy for the administrator role but am unable to retrieve any roles for this user. I'm using dotnet 7.0. I have two problems:. Assigning the Admin to jobTitle works to enforce the policy (see below). That isn't something I want to do long term. Using the URI provided in the documentation does not work. So, I went about trying to see if I could retrieve the assigned roles for a user but failed to do so. Am I missing a setting somewhere that would allow me to see the roles and then use that to enforce administration?

See code snippets below for both.

Thanks!

builder.Services.AddAuthorization(options =>
      {
         options.AddPolicy("RequireAdminRole", policy =>
           {
              // Cannot get below to work.
            //policy.RequireClaim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "Admin");
			  // This works.
              policy.RequireClaim("jobTitle", "Admin");
           });
      });



public static async Task<List<string>> GetRolesforCurrentUser(this            AuthenticationStateProvider provider)    
{ 
	var authState = await provider.GetAuthenticationStateAsync();
    var userIdentity = (ClaimsIdentity)authState.User.Identity;
    var claims = userIdentity.Claims;
    return claims.Where(c => c.Type == ClaimTypes.Role)                    
                 .Select(c => c.Value)
                 .ToList();
}

// The code below always returns zero.
roles = await authProvider.GetRolesforCurrentUser();
Console.WriteLine("Number of roles found: " + roles.Count);

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,166 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,473 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,026 Reputation points
    2023-06-08T19:33:51.4166667+00:00

  2. AKJ 20 Reputation points
    2023-06-09T20:59:22.77+00:00

    I have the following now and it can't get it to work. I created a new client secret and am using its value (not the ID). I am sure everything else is correct. I would really appreciate some help. Thanks!

     //builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
     //   .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAdB2C"));
    
          builder.Services.AddAuthentication(options =>
          {
             options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
             options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
          })
          .AddCookie()
          .AddOpenIdConnect(options =>
          {
             options.SignInScheme = "Cookies";
             options.Authority = "https://login.microsoftonline.com/{my_tenant_id}/v2.0";
             options.RequireHttpsMetadata = true;
             options.ClientId = "my_client_id";
             options.ClientSecret = "Value_of_my_secret";
             options.ResponseType = "code";
             options.UsePkce = true;
             options.Scope.Add("profile");
             options.SaveTokens = true;
             options.TokenValidationParameters = new TokenValidationParameters
             {
                RoleClaimType = "role",
                ValidateIssuer = false
                //RoleClaimType = ClaimTypes.Role
             };
          });
    
          builder.Services.AddAuthorization(options =>
          {
             options.AddPolicy("RequireAdminRole", policy =>
               {
                  // Cannot get below to work. Should not have the admin policy based on job title.
                  policy.RequireClaim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "Admin");
                  //policy.RequireClaim("jobTitle", "Admin");
               });
          });
    

  3. Shweta Mathur 27,456 Reputation points Microsoft Employee
    2023-06-12T08:12:47.1866667+00:00

    Hi @AKJ ,

    Thanks for reaching out.

    Azure AD B2C does not support out-of-box support for role claims for consumer accounts as it would not be feasible for the Administrator to assign the role to consumer identities.

    There are ways to implement RBAC using Azure AD B2C.

    For this purpose, you can use custom claims in Azure AD B2C to allow consumers to select the required role during the signup process which is returned in the token as well.

    You could also leverage Azure AD Custom Policies, which allow you to call a REST API during authentication. This can be used to pass the ObjectId of the user to your API and return the roles to Azure AD B2C. B2C can then issue the roles as a claim into the token.

    Please refer to https://learn.microsoft.com/en-us/azure/active-directory-b2c/add-api-connector-token-enrichment?pivots=b2c-custom-policy for more details.

    Hope this will help.

    Thanks,

    Shweta


    Please remember to "Accept Answer" if answer helped you.