Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Authentication in web API - role claims are missing after validation

I want to base user authorization on Azure AD Application Roles in our Web API, but the roles are not translated into actual claims even though i can see them in the token validation response.

I can see the roles in the ClaimsPrincipal.Current.Claims list, but under the property name roles and not the claims schema http://schemas.microsoft.com/ws/2008/06/identity/claims/role.

I have managed to get the Authorization attribute to recognize the role by setting the RoleClaimType to "roles".

But how do I make Azure return the roles, or configure the API to interpret them, so that HasClaim( ClaimTypes.Role, "AdminRole") returns true?

Controller.cs

[Authorize(Roles = "AdminRole")]
public IEnumerable<Item> Get()
{
    var a = ClaimsPrincipal.Current.HasClaim( ClaimTypes.Role, "AdminRole" ); // false
    var b = User.IsInRole( "AdminRole" ); // true
}

Startup.cs

public void ConfigureAuth( IAppBuilder app )
{
   app.UseWindowsAzureActiveDirectoryBearerAuthentication(
    new WindowsAzureActiveDirectoryBearerAuthenticationOptions
    {
        Tenant = ConfigurationManager.AppSettings[ "ida:Tenant" ],
        TokenValidationParameters =
            new TokenValidationParameters
            {
                ValidAudience = ConfigurationManager.AppSettings[ "ida:Audience" ],
                RoleClaimType = "roles" // makes this work: User.IsInRole( "AdminRole" )
            }
    } );
}

Azure Portal

  • Registered the Web API and native WPF Client Application, and modified the manifest for the Web Api to include a couple of roles. "Azure Portal / App Registrations / Edit manifest"
  • Added/Assigned a few users to the Web Api application and specified one role or another. "Azure Portal / Enterprise Applications / [Name of Application] - Users and groups"

For all who read this far - thanks in advance!

like image 817
MatiasK Avatar asked Oct 30 '22 02:10

MatiasK


1 Answers

The claims emitted by Azure AD are of type "roles", you will need to set the RoleClaimType(in TokenValidationParameters) as roles , then you could make below validations work :

    var a = ClaimsPrincipal.Current.HasClaim("roles", "AdminRole"); 
    var b = User.IsInRole("AdminRole"); 
like image 104
Nan Yu Avatar answered Nov 11 '22 16:11

Nan Yu