Filtering based on policy

Policy-based authorization is a little different than the first two. In this first step, you have to define a policy and then use it with the AuthorizationAttribute. Policies can be configured in the ConfigureServices method in the Startup class, and they can be used to define any criteria on user claims:

    services.AddAuthorization(options => 
{
options.AddPolicy("RequireManagerRole", policy =>
policy.RequireRole("Manager"));
});

And we can use the RequireManagerRole policy as follows:

    [Authorize(Policy ="RequireManagerRole")] 
[HttpGet]
public List<Employee> Get()
{
return GetEmployees();
}

Another example is by reading user claims. For example, if we only allow users to access the EmployeeController, if an AccessAPI claim is present, it can be implemented as follows:

    services.AddAuthorization(options => 
{
options.AddPolicy("RequireAPIAccess", policy =>
policy.RequireClaim("AccessAPI"));
});

Controller can be annotated as follows:

    [Route("api/[controller]")] 
[Authorize(Policy ="RequireAPIAccess")]
public class EmployeeController : Controller
{
}

Multiple claims or roles can be defined as comma-separated. For example, the following example requires access to the EmployeeController if the user has firstname and lastname claims present:

    services.AddAuthorization(options => 
{
options.AddPolicy("RequireProfile", policy =>
policy.RequireClaim("firstname", "lastname"));
});
..................Content has been hidden....................

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