Check Authorization Rules Programatically in ASP.NET Blazor
_Imports.razor
@using Microsoft.AspNetCore.Authorization @using Microsoft.AspNetCore.Components.Authorization
Pages/ProceduralLogic.razor:
@page "/procedural-logic" @inject IAuthorizationService AuthorizationService <h1>Procedural Logic Example</h1> <button @onclick="@DoSomething">Do something important</button> @code { [CascadingParameter] private Task<AuthenticationState>? authenticationState { get; set; } private async Task DoSomething() { if (authenticationState is not null) { var authState = await authenticationState; var user = authState?.User; if (user is not null) { if (user.Identity is not null && user.Identity.IsAuthenticated) { // ... } if (user.IsInRole("Admin")) { // ... } if ((await AuthorizationService.AuthorizeAsync(user, "content-editor")) .Succeeded) { // ... } } } } }
References
https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-6.0#procedural-logic