Search code examples
blazorblazor-server-sideclaims-based-identitymicrosoft-identity-platform

AAD Authorization for Blazor Server Website


I've pushed a copy of the code to the following github repo

I have a new dotnet 6 Blazor server project, created in VS2022 v17.0.4

I'd like to control the Blazor components that get displayed based on the claims of the users logged into the Azure Active Directory.

I've created an app registration with an "Admin" app role, as shown below:

enter image description here

I have two users:

  1. rob.bowman (not a member of Admin)
  2. aza.rob.bowman (is a member of Admin)

enter image description here

So that I can test for the claim, I've added the following to create a policy in the Program.cs file:

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy => policy.RequireClaim("App.Admin"));
});

Note: I've also tried with a claim of "Admin" rather than "App.Admin"

I have the following page that I use to test:

@page "/testadmin"
<h3>TestAdmin</h3>

<AuthorizeView Policy="AdminOnly">
    <p>You can only see this if you satisfy the "AdminOnly" policy.</p>
</AuthorizeView>

My problem is, the protected paragraph is not displayed, regardless of the user I'm logged in as:

enter image description here

To help diagnose, I added a page from this microsoft docs that present the claims. This does show a claim for the role App.Admin

enter image description here


Solution

  • I think you're on the right track. This could be a couple things, but once it's working, you'll be happy.

    1. First, can you verify that you have a <CascadingAuthenticationState> tag in your top level .razor component? This will ensure the auth state is passed down to your .razor components. This likely isn't the issue, but would be!

    2. Second, can you double check your Auth policy? According to this https://learn.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-6.0, your policy requires a claim with name "App.Admin". You may want to try this (require a Role claim with value "App.Admin"):

      {
          options.AddPolicy("AdminOnly", policy => policy.RequireClaim(ClaimTypes.Role, "App.Admin"));
      });
      
      
    3. Lastly, I'd suggest using "Role based" authorization in your .razor components. This will allow the AuthorizationState (in .razor) to be determined by the user's Role claim (App.Admin vs. . You can configure the Role Claim using the options.TokenValidationParameters.RoleClaimType when you set up the authentication in the Blazor app.