AuthorizeView tag with Roles attribute not working, always showing NotAuthorized content
This issue has been moved from a ticket on Developer Community.
I'm trying to use the <AuthorizeView> tag to either show content for user with a specific role, or a message saying "You are not authorized" on a page based on the Role (Claim) for the User (ClaimsIdentity). However, I'm always getting the NotAuthorized content, even when the Role value ("Admin") matches the AuthorizeView tag's Roles attribute value ("Admin").
It should be mentioned that I am manually updating the User (ClaimsIdentity) using a ClaimsTransformation class that inherits from the IClaimsTransformation interface. The public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal) method is used to lookup the user in the database and get their information, including the Role. I add the appropriate information (including the Role) as Claims and return the new ClaimsIdentity. This functionality works fine, and I'm able to set a break point in the page's OnInitialized() method and check the User Claims. There is a Claim of Type "Role" with a value of "Admin". The AuthorizeView tag has a Roles attribute with value of "Admin". But the content displayed is always from the NotAuthorized tag.
Settings page:
@page "/Setting"
@layout MainLayout
@inject ISettingService _settingService
@inject IHttpContextAccessor _httpContextAccessor
<AuthorizeView Roles="Admin">
<Authorized Context="authContext">
...
</Authorized>
<NotAuthorized>
<h1 class="text-danger">Access denied</h1>
<p class="text-danger">You do not have access to this resource.</p>
</NotAuthorized>
</AuthorizeView>
@code {
private IEnumerable<Setting> settings = Enumerable.Empty<Setting>();
protected override void OnInitialized()
{
settings = _settingService.GetSettings();
}
}

Not sure what the problem is here. Any help would be appreciated. Thanks.
Original Comments
Feedback Bot on 2/26/2024, 10:23 PM:
(private comment, text removed)
Original Solutions
(no solutions)
Thanks for contacting us. Can you try to inject an AuthenticationStateProvider instance to the component and query it in your OnInitialized method to see what is the current Authentication state. That may give you some hints for where to look at next.
AuthenticationStateProvider.GetAuthenticationStateAsync()
Not sure if you've solved your problem, but if you haven't, you can try the following in your ClaimsTransformation:
var identity = (ClaimsIdentity)principal.Identity;
identity.AddClaim(new Claim(identity.RoleClaimType, "Admin"))
Using ClaimTypes.Role, if that's what you have used, doesn't always work.
Hope this helps.