Reputation: 1
I created a new ASP.NET Core MVC 6.0 web application, and I defined it to use Microsoft Identity Platform for authentication, as follows:
Now I read this article which show how we can define different roles inside the AD app and assign users to them @
So I accessed the "ad" application inside Azure >> i added a role named "admins", as follow:-
But I am not sure how I can check this role ("admins") based on the login user inside my ASP.NET Core MVC web application? and can i use the [Authorized]
attribute to check those roles? Can anyone help please?
Thanks
Upvotes: -1
Views: 1448
Reputation: 316
In the context of an ASP.NET Core web application, you can intercept the validated incoming JWT token and extract role claims into the identity of the current principal. Check out the code below for reference.
After that you can easily use existing role support in ASP.NET:
Authorize
attribute on Controller or Action:[Authorize(Roles = "admin.all")]
public class MyController: ControllerBase
{
...
}
HttpContext
HttpContext.User.IsInRole("admin.all")
services
.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options =>
{
options.Events = new OpenIdConnectEvents()
{
OnTokenValidated = context =>
{
if (context.Principal.Identity is ClaimsIdentity identity)
{
var tokenRoleClaims = context.SecurityToken?.Claims.Where(c => c.Type == "roles") ?? Array.Empty<Claim>();
var identityRoleClaims = tokenRoleClaims.Select(c => new Claim(identity.RoleClaimType, c.Value));
identity.AddClaims(identityRoleClaims);
}
return Task.CompletedTask;
}
};
});
Upvotes: 0
Reputation: 22472
I agree with @Mohammad Hannan, the token you'll get will have those roles.
I tried to reproduce the same in my environment and got below results:
I created the application same as you and added App role like below:
You can assign this App role to users or groups like below:
Go to Azure Portal -> Azure AD -> Enterprise applications -> Your application -> Users and groups -> Add user/group
Now, add this API permission in application and make sure to grant admin consent like below:
I generated access token using client credentials flow via Postman like below:
POST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
client_id:<appID>
grant_type:client_credentials
scope: api://<appID/.default
client_secret: <secret>
Response:
When I decoded the above token in jwt.ms, I got roles
claim successfully like below:
Upvotes: 1