Skip to content

.NET 8 Blazor @attribute [Authorize(Roles = "Admin")] not working #56773

Closed as not planned
@andrew6767

Description

@andrew6767

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

I am trying to use roles via the authorise attribute @attribute [Authorize(Roles = "Admin")] to limit access to razor pages but this doesn't seem to be working as expected and despite the Claims containing the matching role I'm getting a 401 unauthorised page.

Oddly if I use <AuthorizeView Roles="Admin"> this works and seems to respect the roles in the claims as I would expect. I have also created a page that lists out the claims and the role 'Admin' is listed out so as far as I can see the role is correct.

I am using a custom AuthenticationStateProvider as the end goal is to have the roles coming from an API for my use case but for this example I have just hard coded values to isolate the cause of my error.

`using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.Authorization;

public class CustomAuthStateProvider : AuthenticationStateProvider
{
public override Task GetAuthenticationStateAsync()
{

    var identity = new ClaimsIdentity(new[]
    {
        new Claim(ClaimTypes.Name, "mrfibuli"),
        new Claim(ClaimTypes.Role, "Superuser"),
        new Claim(ClaimTypes.Role, "Admin"),
    }, "Custom Authentication");
    //identity.AddClaim(new Claim(identity.RoleClaimType, "Admin"));

    var user = new ClaimsPrincipal(identity);

    return Task.FromResult(new AuthenticationState(user));
}

}`

Expected Behavior

  • Clone repo https://github.com/andrew6767/DotnetAuthRoleIssue/tree/main
  • Launch with dotnet run
  • Navigate to the view viewUserDetails and see the role 'Admin' is in the Claims
  • Navigate to allowAdminRole and 'You can only see this if you're in the 'Admin' or 'Superuser' role.' should be displayed

Steps To Reproduce

Exceptions (if any)

No response

.NET Version

8.0.303

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions