If the app is required to check authorization rules as part of procedural logic, use a cascaded parameter of type Task<
AuthenticationState>
to obtain the user’s ClaimsPrincipal. Task<
AuthenticationState>
can be combined with other services, such as IAuthorizationService
, to evaluate policies.
@using Microsoft.AspNetCore.Authorization @inject IAuthorizationService AuthorizationService <button @onclick="@DoSomething">Do something important</button> @code { [CascadingParameter] private Task<AuthenticationState> authenticationStateTask { get; set; } private async Task DoSomething() { var user = (await authenticationStateTask).User; if (user.Identity.IsAuthenticated) { // Perform an action only available to authenticated (signed-in) users. } if (user.IsInRole("admin")) { // Perform an action only available to users in the 'admin' role. } if ((await AuthorizationService.AuthorizeAsync(user, "content-editor")) .Succeeded) { // Perform an action only available to users satisfying the // 'content-editor' policy. } } }
References
https://docs.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-6.0#procedural-logic