Share via

Blazor Server load user permissions once

Matthew Holton 331 Reputation points
2023-03-06T17:52:27.9066667+00:00

I am using Azure Identity for authentication in my Blazor Server application. I access control information about the user in my applications database. I am looking for a way to load that information for AuthorizedView policies or manage flow control. I am seeking a way to minimize how often I hit the database to read this information.

it occurs to me that the access token would be an ideal place to store custom claims.

I've tried using:

  • IClaimsTransformation This appears to be a per request mechanism, so that doesn't meet my goal. Just to load my default page, the database is called 5 times for this information. I assume this is for each of the components with an <AuthorizedView> tag in the composition. builder.Services.AddScoped<IClaimsTransformation, MyClaimsTransformation>();
  • UseMiddleware This only calls the database once to load my default page. However, the browser reports No 'Access-Control-Origin' header is present int he requested resource. And then reports Failure to load resource from login.microsoftonline.com. Searching the interwebs, it seems that I need to add a Cors Policy e.g.
   builder.Services.AddCors(options =>
   {
     options.AddPolicy("AllowOrigin", builder => 
       builder.WithOrigin("https://localhost:port")
       .AllowAnyHeader()
       .AllowAnyMethod()
   };

...

   app.UserCors("AllowOrigin");
   
   ...
   
   app.UserAuthentication();
   app.UseMiddleware<CustomeClaimsMiddleware>();
   app.UseAuthorization();

There are a lot of differing opinions for this. Some say to use AllowAnyOrigin and/or AllowCredentials; however, none of them seem to do the job.

So perhaps the middleware approach doesn't load more than once because it failed the first time.

Anyone have any other suggestions?

Developer technologies | .NET | Blazor
Microsoft Security | Microsoft Entra | Microsoft Entra ID

Answer accepted by question author

Bruce (SqlWork.com) 84,086 Reputation points
2023-03-06T18:51:49.1533333+00:00

with blazor server, there is only one request for the life of the application. your middleware should be a transient or scoped object that calls the database and caches the result in itself. it should use an injected identity.

though I generally would add custom claims to the identity with OnTokenValidated callback.

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.