My Blazor Web Assembly app is registered in Azure Active Directory (single tenant my organization only).
Groups claim has been added to the token configuration with the optional setting to emit groups as role claims.
I am able to run the app and authenticate, but any page with Authorize attribute defining specific roles within my organization shows the "You are not authorized to access this resource." message configured in App.razor for Not Authorized
I have confirmed that I am receiving the roles Claim, but is a json array of role names.
I have tried creating a custom AccountClaimsPrincipalFactory where I deserialize the roles claim value and add a new claim for each role name in the array, but still get the same result.
public class CustomAccountClaimsPrincipalFactory : AccountClaimsPrincipalFactory<RemoteUserAccount>
{
public CustomAccountClaimsPrincipalFactory(IAccessTokenProviderAccessor accessor)
: base(accessor) { }
public async override ValueTask<ClaimsPrincipal> CreateUserAsync(RemoteUserAccount account, RemoteAuthenticationUserOptions options)
{
var user = await base.CreateUserAsync(account, options);
if (!user.Identity.IsAuthenticated)
{
return user;
}
if (user.Identity is not ClaimsIdentity identity)
{
return user;
}
var roleClaims = identity.FindAll("roles");
if (roleClaims is null || !roleClaims.Any())
{
return user;
}
foreach (var roleClaim in roleClaims)
{
try
{
var roleNames = JsonConvert.DeserializeObject<string[]>(roleClaim.Value);
foreach (var roleName in roleNames)
{
identity.AddClaim(new Claim(ClaimTypes.Role, roleName));
}
}
catch
{
// continue
}
}
return user;
}
}
And in my Program.cs
_ = builder.Services.AddMsalAuthentication(options =>
{
Configuration.Bind("AzureAD", options.ProviderOptions.Authentication);
options.ProviderOptions.DefaultAccessTokenScopes.Add("app-scope");
})
.AddAccountClaimsPrincipalFactory<CustomAccountClaimsPrincipalFactory>();
And on my page
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize(Roles="GROUP1, GROUP2, GROUP3")]
I have confirmed that the AccountClaimsPrincipalFactory has added each role as a new claim and I am able to view the user's profile information and get a true response from user.IsInRole("GROUP1");, however, on any page with the [Authorize] attribute, I still see the same error:
You are not authorized to access this resource
Am I missing something? Any suggestions?