DEV Community

Sven Glöckner
Sven Glöckner

Posted on • Updated on

Using custom claims for Azure AD B2C roles

As we already know, currently Azure AD B2C does not support roles out-of-the-box. But I think there is a fairly easy way to workaround this limitation by using a custom claim for this requirement.

First, add a custom claim in Azure AD B2C portal - name it "Role". Remember to check this claim in your SignIn/SignUp user workflow so that it will be put into the authentication token.

Then you can add a custom authorization Policy in your .NET Core project:

services.AddAuthorization(options =>
{
      options.AddPolicy("Admin", policy =>
         policy.RequireClaim("extension_Role", "Admin"));
});
Enter fullscreen mode Exit fullscreen mode

Afterwards you're able to use this in your controller or Page (I'm using Blazor).

[Authorize(Policy = "Admin")]
Enter fullscreen mode Exit fullscreen mode

And voilà - that's it!

Top comments (5)

Collapse
 
aswque profile image
aswque

Thank you for that.
Unfortunately, it didn't works for me, it seems like that the extension_Role claim is not been read (the claim is check on my SignIn/SignUp policy). I am using .NetCore3.1 and services.AddSignIn to call the login page. Can you please share how you are doing the authentication part (services.Configure and services.AddAuthentication)?

Collapse
 
p_gururani profile image
Pradeep Gururani

You also need to call app.UseAuthorization(); in addition to adding this policy. You need to add custom attribute Role to your User object. Have you done that?

Collapse
 
p_gururani profile image
Pradeep Gururani

This worked very well as described, however how about the scenario when user may have multiple roles?

Collapse
 
sven5 profile image
Sven Glöckner

Hi Pradeep, thanks for your reply.
It's possible to apply the same claim type multiple times to a ClaimsPrincipal. So that means you could easily write some code to set multiple roles on your user.

However, the AuthorizeAttribute cannot check multiple roles at the same time. You could write your own attribute that checks for combination of roles. See this article on stackoverflow.

Collapse
 
kumudumushidev profile image
kumudumushi-dev

Thank you for this.
But how to get the roles custom policy from azure B2C and can we view the roles assigned from the blazor page?