Blazor webassembly, check if Policy exists

Posted 3 years ago by Rubeesh
Edited 2 years ago
0

In my blazor webassembly project i am trying to load poilicies from webapi, so that admins can set policies(permissions) for each roles.

The problem is that the Authorization policy validation on the first page is done even before getting the response from httpclient request as it is async call, and i get an error the policy does not exists.

Is there any way that i can execute httpclient request synchronously OR check if the policy exists and wait till policy initialization is complete.

JSON Object:

[
{"policy": "Administration","roles": ["admin"]},
{"policy": "FinanceTransaction","roles": ["admin,accountant"]},
.....
]

Policy Initialization:

public class Program
   {
       public static async Task Main(string[] args)
       {
           var builder = WebAssemblyHostBuilder.CreateDefault(args);
           builder.RootComponents.Add<App>("#app");
           var baseAddress = builder.Configuration["apiUrl"];
           builder.Services.AddHttpClient("Anonymous", client => client.BaseAddress = new Uri(baseAddress));
           builder.Services.AddHttpClient("Protected", client => client.BaseAddress = new Uri(baseAddress));
           builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("Protected"));
           builder.Services.AddAuthorizationCore(async options =>
           {
               var httpClientFactory = builder.Build().Services.GetRequiredService<IHttpClientFactory>();
               var http = httpClientFactory.CreateClient("Anonymous");
              var tasks = await http.GetFromJsonAsync<IEnumerable<PolicyRoles>>($"AppPolicy");
               foreach (var task in tasks)
               {
                   AppLoadStatus.PolicyLoaded = true;
                   OnPolicyLoaded.Invoke();
                   if (task.Roles.Any())
                       options.AddPolicy(task.Policy, policy => { policy.RequireRole(task.Roles); });
               }
           });
           await builder.Build().RunAsync();
       }
   }

Razor Page:

@page "/Items/"
@attribute [Authorize(Policy = "FinanceTransaction")]
<div class="col col-lg-9">
   @if (items == null)
     {
        <LoadingSpinner LoadFailed="@loadFailed" />
     }
   else
     {
        .....
        .....
      }
<div>

If i try to load the above page directly i get the error:

crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]

     Unhandled exception rendering component: The AuthorizationPolicy named: 'FinanceTransaction' was not found

But if i wait for policy initialization and navigate to other pages everything would work fine.

Can any one help me to resolve the issue. Or is there any other better approach for this

Someone is typing...

Post a Reply

You must be logged in to add a new post.
Number of online users: 1
An error has occurred. This application may no longer respond until reloaded. Reload 🗙