Authorization in Blazor WASM - policies don't work

Viewed 536

So when I add policy-based authorization to the Startup.cs file and then add AuthorizeView to my Blazor page, I get an error:

crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: The AuthorizationPolicy named: 'SuperAdmin' was not found.
System.InvalidOperationException: The AuthorizationPolicy named: 'SuperAdmin' was not found.
   at Microsoft.AspNetCore.Authorization.AuthorizationPolicy.CombineAsync(IAuthorizationPolicyProvider policyProvider, IEnumerable`1 authorizeData)
   at Microsoft.AspNetCore.Components.Authorization.AuthorizeViewCore.IsAuthorizedAsync(ClaimsPrincipal user)
   at Microsoft.AspNetCore.Components.Authorization.AuthorizeViewCore.OnParametersSetAsync()
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle) blazor.webassembly.js:1:14889

But in my Startup:

services.AddAuthorization(o =>
            {
                o.AddPolicy("SuperAdmin", policy => policy.RequireClaim("SuperAdmin"));
                o.AddPolicy("CountyAdmin", policy => policy.RequireClaim("CountyAdmin"));
            });

When I take a look at the 'Claims' for the user, the claims from the DB don't show. They are there though.

So, why, if I've declared the policies in startup does the razor page marked with the Policies above give me this error?

Thanks all!!!

1 Answers

I got it to work by adding the following the the Client's Program.cs in the Main function.

builder.services.AddAuthorizationCore(o =>
{
  o.AddPolicy("SuperAdmin", policy => policy.RequireClaim("SuperAdmin"));
  o.AddPolicy("CountyAdmin", policy => policy.RequireClaim("CountyAdmin"));
});

What you had setup authorization on the server. This does it for the client.

Related