meta info

Role Based Policy Authentication

By Ziya Mollamahmut

What is it that causes a page to redirect to Login and another to not?

  • If the page or controller is configured to allow anonymous it will not redirect to login
[AllowAnonymous]
public class HomePage : PageModel
{
    //...
}
  • If the page/folder or area is configured to allow authorized users only, either by using [Authorize] attribute or in startup.cs it will redirect the user to the login page if he/she is not logged in.
[Authorize]
public ContactModel : PageModel
{
    // ...
}

Here is a sample configuration for authorization in startup, where we do create a role based policy named RequireAdmins for a role name Admins:

services.AddRazorPages()
    .AddRazorPagesOptions(ops =>
    {
        ops.Conventions.AuthorizeAreaFolder("Panel", "/", "RequireAdmins");
        ops.Conventions.AuthorizeFolder("/", "RequireAdmins");
        ops.Conventions.AllowAnonymousToAreaPage("Identity", "/Account/AccessDenied");
    });

services.AddAuthorization(ops =>
{
    ops.AddPolicy("RequireAdmins", policy => policy.RequireRole("Admins"));
});