Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to authorize access to all files in a folder via roles

I'm upgrading some initial razor code into asp .net razor pages with .net core 5.0. I've been through many examples on Microsoft Learn, but it seems that I have to set attributes in all of my .cshtml.cs files. that feels just sloppy and error prone because something will be forgotten somewhere.

In .NET 4.x Razor syntax, I have an _PageStart.cshtml file, I check the user's role, and I redirect them to the login page if they are not in a particular role. I'd like to do the same in asp .net core using a single file or configuration. I don't want to put an attribute on every pagemodel file, that just seems sloppy. I imagine that I would do something like:

options.Conventions.AuthorizeFolder("/Club", "ClubAdmin");

where ClubAdmin is a role in the application and Club is a folder that contains a bunch of razor pages and sub folders. Is this possible?

like image 768
Wallace B. McClure Avatar asked Nov 29 '25 06:11

Wallace B. McClure


1 Answers

To do this, you can define a policy in your Startup.cs file that checks for a role and then configure razor pages to Authorize that folder for that specific policy:

//define the admin policy
services.AddAuthorization(options =>
{
    options.AddPolicy("AdminPolicy", policy => policy.RequireRole("Administrator"));
});

services.AddRazorPages(options =>
{
    options.Conventions.AuthorizeFolder("/Admin", "AdminPolicy");
});

The RequireRole extension method injects a RolesAuthorizationRequirement handler that will validate for the given role during authorization

like image 131
pnavk Avatar answered Dec 02 '25 04:12

pnavk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!