In a Blazor application, custom role-based authorization for Razor Pages can be implemented by creating a custom authorization attribute and applying it to the Razor Page or its handler methods. Below is a step-by-step guide on how to create and use such an attribute:
Create a Custom Authorization Attribute:
Define a custom attribute by inheriting from AuthorizeAttribute
and implementing your role-checking logic.
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Linq; public class CustomRoleAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter { private readonly string[] _roles; public CustomRoleAuthorizeAttribute(params string[] roles) { _roles = roles; } public void OnAuthorization(AuthorizationFilterContext context) { var user = context.HttpContext.User; if (!user.Identity?.IsAuthenticated ?? true) { // User is not authenticated context.Result = new Microsoft.AspNetCore.Mvc.ForbidResult(); return; } if (!_roles.Any(role => user.IsInRole(role))) { // User does not have the required role context.Result = new Microsoft.AspNetCore.Mvc.ForbidResult(); } } }
Apply the Custom Attribute to a Razor Page:
You can apply this attribute to Razor Pages or their handler methods.
@page @attribute [CustomRoleAuthorize("Admin", "Manager")] @using Microsoft.AspNetCore.Authorization <h3>Admin or Manager Access Only</h3> <p>This content is visible only to users with Admin or Manager roles.</p>
Example for a specific handler method:
@page @attribute [Authorize] @using Microsoft.AspNetCore.Authorization <h3>Handler-Specific Role Authorization</h3> @code { [CustomRoleAuthorize("Admin")] public void HandleAdminContent() { // Logic for Admin content } }
Register Authentication Middleware:
Ensure that authentication and authorization are configured in your
Startup.cs
or Program.cs
file.builder.Services.AddAuthentication("YourExampleAuthenticationScheme") .AddCookie("YourExampleAuthenticationScheme", options => { options.LoginPath = "/Login"; }); builder.Services.AddAuthorization();
Now you can test on your localhost Blazor app, login with different roles, and ensure that the role-based restrictions work as expected.
This implementation allows you to define flexible, reusable role-based access rules while maintaining a clean and modular structure in your Blazor application.