Creating an authorization policy

ASP.NET Core provides a strong and extensible infrastructure for creating authorization rules and policies. In an attempt to keep this chapter as simple and clear as possible, I will show you the most straightforward way to create an authorization rule that will only allow users that have been registered for more than a year to add categories.

To add authorization policies, use the AddAuthorization extension method inside the ConfigureServices method, and add a policy by specifying its name and the logic it should perform: 

services.AddAuthorization(options => 
options.AddPolicy("ExpereincedUser", (AuthorizationPolicyBuilder policy) =>{ /* policy logic */}));

For our case, where we need to check that the authenticated user has more than one year of experience, we need to extract the registration date claim and then parse its value to a DateTime format that we could check. AuthorizationPolicyBuilder includes a few methods that can help you check for simple conditions:

  • RequireRole: Checks that the current user has a specified role
  • RequireClaim: Checks that the current user has a certain claim, and that its value is part of the allowed group of values 
  • RequireUserName: Checks that the current user has the specified username
  • RequireAssertion: Allows you to define a complex logic condition

Since our ExperiencedUser policy requires checking not only that the user has the registration date claim, but also that its value is from more than a year ago, we are going to use the RequireAssertion method, like so:

policy.RequireAssertion(context =>
{
var registrationClaimValue = context.User.Claims.SingleOrDefault(c=>c.Type == "registration-date")?.Value;
if (DateTime.TryParseExact(registrationClaimValue, "yy-MM-dd",CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal,out var registrationTime))
{
return registrationTime.AddYears(1) < DateTime.UtcNow;
}
return false;
})

The preceding code extracts the registration date claim, and then tries to parse it and checks if its value is of a date earlier than a year ago. 

To apply the policy to a controller action, you just need to specify the policy name in the Authorize attribute that decorates the method or class, as shown here:

[Authorize(Policy = "ExperiencedUser")]
[HttpPost("categories")]
public Task<ActionResult> AddCategory([FromBody] NewCategoryDTO newCategory)
{
...
}
..................Content has been hidden....................

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