Custom policies

Custom requirements can also be implemented to handle any requirement. We can define custom requirements by implementing the IAuthorizationRequirement interface. Here is our custom requirement that only allows users if they are based in GCC countries, namely Saudi Arabia, Kuwait, United Arab Emirates, Qatar, Bahrain, and Oman:

    public class BaseLocationRequirement :
Microsoft.AspNetCore.Authorization.IAuthorizationRequirement
{
public BaseLocationRequirement(List<string> locations)
{
BaseLocation = locations;
}

public List<string> BaseLocation { get; set; }
}

Once the requirement is set up, we need to define the handler that evaluates the requirement:

    public class BaseLocationHandler : Microsoft.AspNetCore
.Authorization.AuthorizationHandler<BaseLocationRequirement>
{
protected override Task
HandleRequirementAsync(AuthorizationHandlerContext
context, BaseLocationRequirement requirement)
{
if (!context.User.HasClaim(c => c.Type ==
ClaimTypes.Country))
{
return Task.CompletedTask;
}

string country = context.User.FindFirst(
c => c.Type == ClaimTypes.Country).Value;

List<string> gccCountries = requirement.BaseLocation;

if (gccCountries.Contains(country))
{
context.Succeed(requirement);
}
return Task.CompletedTask;

}
}

The preceding code implements the HandleRequirementAsync method that evaluates the requirement and if the country lies within the GCC countries, the requirement will be succeeded.

This new custom requirement can be added in the ConfigureServices method as follows and can be used in the AuthorizeAttribute in controller or action level:

    services.AddAuthorization(options =>
options.AddPolicy("AnyGCCCountry",
policy => policy.Requirements.Add(new
BaseLocationRequirement(new List<string> {
"Saudi Arabia", "Kuwait", "United Arab Emirates",
"Qatar", "Bahrain", "Oman" }))));

Finally register the BaseLocationHandler with AuthorizationHandler using Dependency Injection (DI) .

..................Content has been hidden....................

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