meta info
- Title: Asp.Net Core - Role Based Policy Authorization
- Keywords: asp.net,core,authentication,role,policy,login,time,custom login,identity
- Description: How to create a role based policy authorization for Asp.Net Core.
- Author: Ziya Mollamahmut
- Date: 14-Apr-2021
- Image: https://github.com/LazZiya/Docs/raw/master/Miscellaneous/v1.0/images/ziya-logo.png
- Image-alt: Miscellaneous Logo
- Version: v1.0
- 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 instartup.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"));
});