Reputation: 8711
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:
I have two users:
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:
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
Upvotes: 0
Views: 876
Reputation: 2256
I think you're on the right track. This could be a couple things, but once it's working, you'll be happy.
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!
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"));
});
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.
Upvotes: 1