I'm using Azure AD/Entra for OIDC authentication:
services
.AddAuthentication()
.AddMicrosoftIdentityWebApp(
configuration.GetSection("AzureAd"),
openIdConnectScheme: "MySchemeName",
cookieScheme: null,
displayName: "MySchemeName");
My app registration has an app role defined, and assigned to a user.
On my ChallengeResult
callback, I can see the role as a claim in the ExternalLoginInfo
object in the Principal.Claims
property that is returned from the signInManager.GetExternalLoginInfoAsync()
method. So clearly the role is correctly in the token.
However, I have a policy defined as:
options.AddPolicy("MyPolicy", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim(ClaimTypes.Role, "AzureAppRoleName");
});
And when I navigate to a page with this policy defined as [Authorize(Policy = "MyPolicy")]
I get a 403.
If I set a breakpoint in some custom middleware, I can see that the HttpContext.User
has some claims, but not the role claims.
How do I make sure the role claims returned in the token get assigned to the principal?
See my codes below, when I use mypolicy
everything worked well, but if I use [Authorize(Policy = "mypolicy2")]
in my Controller action method, I got access denied issue.
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("mypolicy", policy => policy.RequireRole("Tiny.AccessEndpoint"));
//options.AddPolicy("mypolicy2", policy => policy.RequireClaim(ClaimTypes.Role, "Tiny.AccessEndpoint"));
});
So that I'm afraid you should change policy.RequireClaim(ClaimTypes.Role
to policy.RequireRole