Role-based authorization

When a ClaimsPrincipal object is created, like we did previously, there is a property called IsInRole. This property provides us access to the Roles of the user. Role-based authorization checks are declarative. They can be used in the same way, using the [Authorize] attribute that we have seen, by passing in the Roles parameter:

[Authorize(Roles = "Administrator,ITAdminsitrator")]
public class UserAdministrationController : Controller
{
….
}

In the preceding example, all the actions of UserAdministrationController are accessible to authenticated users with either the Adminsitrator or ITAdministrator roles. So, we can provide multiple roles as comma-separated values in the Roles parameter and they will be treated as an or condition. You can further restrict access to only one of the roles by providing the attribute at the action level.

 What if I need to have an and condition between roles? The following snippet will ensure that actions are accessible only if the authenticated user has both ITAdministrator and Administrator roles:

[Authorize(Roles = "ITAdminsitrator")]
[Authorize(Roles = "Administrator")]
public class UserAdministrationController : Controller
{
….
}

If we look at the overloads of the [Authorize] attribute, there is an overload that accepts the following policy:

Policy-based role checks are also supported and can be done at the Startup in the ConfigureServices() method while configuring authorization:

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdminRole", policy =>
policy.RequireRole("Administrator"));
});
}

[Authorize(Policy="RequireAdminRole")]
public IActionResult HighPreviligeAction()
{
return View();
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset