Setup role based Folder/AreaFolder authorization in ASP.Net Core Razor pages
Authorizing razor pages individually using [Authorize(Role="Admins")]
attribute requires using the attribute on each page individually, a better approach is to manage authorizations in startup class for folders or area folders.
1. Register role based policies in startup.cs under ConfigureServies method:
services.AddAuthorization(ops =>
{
ops.AddPolicy("Admins", policy =>
{
policy.RequireRole("Admins");
});
ops.AddPolicy("Users", policy =>
{
policy.RequireRole("Users");
});
});
2. Configure folder authorization:
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddRazorPagesOptions(ops =>
{
ops.Conventions.Add(new GlobalTemplatePageRouteModelConvention());
ops.Conventions.AuthorizeAreaFolder("AreaName", "/FolderPath/", "Admins");
ops.Conventions.AuthorizeFolder("/FolderPath/", "Users");
});