Claim Based And Policy-Based Authorization With ASP.NET Core 2.1

Authorization is a process of determines whether a user is able to access the system resource. In my previous article, I have explained the role-based authorization. The identity membership system allows us to map one or more roles with a user and based on role, we can do authorization. In this article, I will explain how to do authorization based on policy and claim.

Introduction
 
Authorization is a process of determining whether the user is able to access the system resource. In my previous article, I have explained role-based authorization. The identity membership system allows us to map one or more roles with the user;  based on the role, we can do authorization. In this article, I will explain how to do authorization based on policy and claim.
 
Claim-based authorization
 
Claims are the user data and they are issued by a trusted source. If we are working with token-based authentication, a claim may be added within a token by the server that generates the token. A claim can have any kind of data such as "DateOfJoining", "DateOfBirth", "email", etc. Based on a claim that a user has, a system provides the access to the page, which is called Claim based authorization. For example, the system will provide access to the  page, if the user has a "DateOfBirth" claim. In short, claim based authorization checks the value of the claim and allows access to the system resource based on the value of a claim.
 
To demonstrate with an example, I have created 2 users and associated some claim identity with the user. I have achieved this by using the following code.
  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)  
  2. {  
  3.     ....  
  4.     ....  
  5.   
  6.     app.UseAuthentication();  
  7.   
  8.     app.UseMvc(routes =>  
  9.     {  
  10.         routes.MapRoute(  
  11.             name: "default",  
  12.             template"{controller=Home}/{action=Index}/{id?}");  
  13.     });  
  14.     CreateUserAndClaim(serviceProvider).Wait();  
  15. }  
  16. private async Task CreateUserAndClaim(IServiceProvider serviceProvider)  
  17. {  
  18.     var UserManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();  
  19.     IdentityUser user = await UserManager.FindByEmailAsync("jignesh@gmail.com");  
  20.   
  21.     if (user == null)  
  22.     {  
  23.         user = new IdentityUser()  
  24.         {  
  25.             UserName = "jignesh@gmail.com",  
  26.             Email = "jignesh@gmail.com",  
  27.         };  
  28.         await UserManager.CreateAsync(user, "Test@123");  
  29.     }  
  30.   
  31.     var claimList = (await UserManager.GetClaimsAsync(user)).Select(p => p.Type);  
  32.     if (!claimList.Contains("DateOfJoing")){  
  33.         await UserManager.AddClaimAsync(user, new Claim("DateOfJoing""09/25/1984"));  
  34.     }  
  35.     if (!claimList.Contains("IsAdmin")){  
  36.         await UserManager.AddClaimAsync(user, new Claim("IsAdmin""true"));  
  37.     }  
  38.   
  39.     IdentityUser user2 = await UserManager.FindByEmailAsync("rakesh@gmail.com");  
  40.   
  41.     if (user2 == null)  
  42.     {  
  43.         user2 = new IdentityUser()  
  44.         {  
  45.             UserName = "rakesh@gmail.com",  
  46.             Email = "rakesh@gmail.com",  
  47.         };  
  48.         await UserManager.CreateAsync(user2, "Test@123");  
  49.     }  
  50.     var claimList1 = (await UserManager.GetClaimsAsync(user2)).Select(p => p.Type);  
  51.     if (!claimList.Contains("IsAdmin"))  
  52.     {  
  53.         await UserManager.AddClaimAsync(user2, new Claim("IsAdmin""false"));  
  54.     }  
  55. }  
 
 
Claim-based authorization can be done by creating policy; i.e., create and register policy stating the claims requirement. The simple type of claim policy checks only for the existence of the claim but with advanced level, we can check the user claim with its value. We can also assign more than one value for a claim check.
 
In this following example, I have created the policy that checks the 2 claims for user authorization: one for "DateofJoining" and another for "IsAdmin". Here "DateofJoining" is a simple type of claim; i.e., it only checks if a claim exists or not whereas "IsAdmin" claim checks with its value.
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.     ....  
  4.     ....  
  5.     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);  
  6.     services.AddAuthorization(options =>  
  7.     {  
  8.         options.AddPolicy("IsAdminClaimAccess", policy => policy.RequireClaim("DateOfJoing"));  
  9.         options.AddPolicy("IsAdminClaimAccess", policy => policy.RequireClaim("IsAdmin""true"));  
  10.     });  
  11. }  
We can apply this policy to Authorize attribute using "Policy" property. Here we have to specify the name of the policy.
  1. [Authorize(Policy = "IsAdminClaimAccess")]  
  2. public IActionResult TestMethod1()  
  3. {  
  4.     return View("MyPage");  
  5. }  
We can also apply multiple policies to the controller or action. To grant access, all policies must be passed.
  1. [Authorize(Policy = "IsAdminClaimAccess")]  
  2. [Authorize(Policy = "NonAdminAccess")]  
  3. public IActionResult TestMethod2()  
  4. {  
  5.     return View("MyPage");  
  6. }  
In the above examples, we assign claims to the user and authorize by creating the policy. Alternatively, claims can also be assigned to a user role, so using this, an entire group of users can access the page or resources. I have made a small change in my code that generates user, user role and adds claims to the roles.
  1. private async Task CreateUserAndClaim(IServiceProvider serviceProvider)  
  2. {  
  3.     var UserManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();  
  4.     var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();  
  5.   
  6.     //Added Roles  
  7.     var roleResult = await RoleManager.FindByNameAsync("Administrator");  
  8.     if (roleResult == null)  
  9.     {  
  10.         roleResult = new IdentityRole("Administrator");  
  11.         await RoleManager.CreateAsync(roleResult);  
  12.     }  
  13.   
  14.     var roleClaimList = (await RoleManager.GetClaimsAsync(roleResult)).Select(p => p.Type);  
  15.     if(!roleClaimList.Contains("ManagerPermissions"))  
  16.     {  
  17.         await RoleManager.AddClaimAsync(roleResult, new Claim("ManagerPermissions""true"));  
  18.     }  
  19.   
  20.     IdentityUser user = await UserManager.FindByEmailAsync("jignesh@gmail.com");  
  21.   
  22.     if (user == null)  
  23.     {  
  24.         user = new IdentityUser()  
  25.         {  
  26.             UserName = "jignesh@gmail.com",  
  27.             Email = "jignesh@gmail.com",  
  28.         };  
  29.         await UserManager.CreateAsync(user, "Test@123");  
  30.     }  
  31.     await UserManager.AddToRoleAsync(user, "Administrator");  
  32.     ....  
  33.     ....  
  34.     ....  
  35.     ....  
  36. }   
 
 
Same as the above mentioned code, we can create a policy for the role-based claim and applied to controller or action method by using Authorize attribute.
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.     ...  
  4.     ...  
  5.     services.AddAuthorization(options =>  
  6.     {  
  7.         ...  
  8.         ...  
  9.         options.AddPolicy("RoleBasedClaim", policy => policy.RequireClaim("ManagerPermissions""true"));  
  10.     });  
  11. }  
  1. [Authorize(Policy = "RoleBasedClaim")]  
  2. public IActionResult TestMethod3()  
  3. {  
  4.     return View("MyPage");  
  5. }  
Policy-based authorization
 
The .NET Core Framework allows us to create policies to authorization. We can either use pre-configured policies or can create a custom policy based on our requirement.
 
In the role-based authorization and claims-based authorization (refer to the preceding section), we are using pre-configured policies such as RequireClaim and RequireRole. The policy contains one or more requirements and registers in AddAuthorization service configuration.
 
Authorization Requirements
 
The requirement is the collection of data which can be used to evaluate the user principal. To create the requirement, the class must implement interface IAuthorizationRequirement that is an empty interface. The requirement does not contain any data and evaluation mechanism.
 
Example
In the following example, I have created a requirement for minimum time spent for the organization.
  1. public class MinimumTimeSpendRequirement: IAuthorizationRequirement  
  2. {  
  3.     public MinimumTimeSpendRequirement(int noOfDays)  
  4.     {  
  5.         TimeSpendInDays = noOfDays;  
  6.     }  
  7.   
  8.     protected int TimeSpendInDays { get; private set; }  
  9. }  
Authorization handlers
 
The authorization handler contains the evaluation mechanism for properties of requirement. The handler must evaluate the requirement properties against the AuthorizationContext and decide if the user is allowed to access the system resources or not. One requirement may have multiple handlers. The authorization handler must inherit from AuthorizationHandler<T> class; here T is a type of requirement class.
 
Example
In the following example code, I have created a handler for the requirement MinimumTimeSpendRequirement. This handler first looks for the date of joining claim (DateOfJoining). If this claim does not exist for the user, we can mark this as an unauthorized request. If the user has a claim then we calculate how many days spent by user within the organization. If this meets the requirement passed in authorization service then the user is authorized to access. I have the call context.Succeed(), it means that the user fulfilled all the requirements.
  1. public class MinimumTimeSpendHandler : AuthorizationHandler<MinimumTimeSpendRequirement>  
  2. {  
  3.     protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MinimumTimeSpendRequirement requirement)  
  4.     {  
  5.         if (!context.User.HasClaim(c => c.Type == "DateOfJoining"))  
  6.         {  
  7.             return Task.FromResult(0);  
  8.         }  
  9.   
  10.         var dateOfJoining = Convert.ToDateTime(context.User.FindFirst(  
  11.             c => c.Type == "DateOfJoining").Value);  
  12.   
  13.         double calculatedTimeSpend = (DateTime.Now.Date - dateOfJoining.Date).TotalDays;  
  14.               
  15.         if (calculatedTimeSpend >= requirement.TimeSpendInDays)  
  16.         {  
  17.             context.Succeed(requirement);  
  18.         }  
  19.         return Task.FromResult(0);  
  20.     }  
  21. }  
Handler registration
 
The handle that is using authorization must register in service collection. We can add the service collection by using "services.AddSingleton<IAuthorizationHandler, ourHandlerClass>()" method where we need to pass handler class.
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);  
  4.      services.AddAuthorization(options =>  
  5.      {  
  6.         ...  
  7.         ...  
  8.         options.AddPolicy("Morethan365DaysClaim", policy => policy.Requirements.Add(new MinimumTimeSpendRequirement(365)));  
  9.      }  
  10.      services.AddSingleton<IAuthorizationHandler, MinimumTimeSpendHandler>();  
  11. }  

Handler does not return any value, so a handler indicates the success by calling context.Succeed(requirement) method, here whatever requirement we are passing that has been successfully validated. If we do not call context.Succeed method, handler automatically fails or we can call context.Fail() method.
 
Multiple handlers for a Requirement
 
In some cases, we are required to evaluate requirements based on OR condition, we can implement multiple handlers for the single requirement. For example, we have a requirement, like a page can be accessed by the user if he spends at least 365 days in an organization or a user from the HR department. In this case, we have a single requirement to access the page, not multiple handlers for validating a single requirement.
 
Example
  1. using Microsoft.AspNetCore.Authorization;  
  2. using System;  
  3. using System.Threading.Tasks;  
  4.   
  5. namespace ClaimBasedPolicyBasedAuthorization.Policy  
  6. {  
  7.     public class PageAccessRequirement : IAuthorizationRequirement  
  8.     {  
  9.     }  
  10.   
  11.     public class TimeSpendHandler : AuthorizationHandler<PageAccessRequirement>  
  12.     {  
  13.         protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PageAccessRequirement requirement)  
  14.         {  
  15.             if (!context.User.HasClaim(c => c.Type == "DateOfJoining"))  
  16.             {  
  17.                 return Task.FromResult(0);  
  18.             }  
  19.   
  20.             var dateOfJoining = Convert.ToDateTime(context.User.FindFirst(  
  21.                 c => c.Type == "DateOfJoining").Value);  
  22.   
  23.             double calculatedTimeSpend = (DateTime.Now.Date - dateOfJoining.Date).TotalDays;  
  24.   
  25.             if (calculatedTimeSpend >= 365)  
  26.             {  
  27.                 context.Succeed(requirement);  
  28.             }  
  29.             return Task.FromResult(0);  
  30.         }  
  31.     }  
  32.     public class RoleCheckerHandler : AuthorizationHandler<PageAccessRequirement>  
  33.     {  
  34.         protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PageAccessRequirement requirement)  
  35.         {  
  36.             if (!context.User.HasClaim(c => c.Type == "IsHR"))  
  37.             {  
  38.                 return Task.FromResult(0);  
  39.             }  
  40.   
  41.             var isHR = Convert.ToBoolean(context.User.FindFirst(c => c.Type == "IsHR").Value);  
  42.   
  43.             if (isHR)  
  44.             {  
  45.                 context.Succeed(requirement);  
  46.             }  
  47.             return Task.FromResult(0);  
  48.         }  
  49.     }  
  50. }  
Here, we need to register both the handlers. If any one handler of the two succeeds , the policy evaluation has succeeded.
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.     ....  
  4.     ....  
  5.     ....  
  6.     services.AddAuthorization(options =>  
  7.     {  
  8.         ....  
  9.         ....  
  10.         options.AddPolicy("AccessPageTestMethod5", policy => policy.Requirements.Add(new PageAccessRequirement()));  
  11.     });  
  12.     ...  
  13.     ...  
  14.     services.AddSingleton<IAuthorizationHandler, TimeSpendHandler>();  
  15.     services.AddSingleton<IAuthorizationHandler, RoleCheckerHandler>();  
  16. }   
Using RequireAssertion policy builder method, we can add simple expression for the policy without requirement and handler. The code mentioned for he above example can be re-written as following
  1. services.AddAuthorization(options =>  
  2. {  
  3.     ...  
  4.     ....  
  5.     options.AddPolicy("AccessPageTestMethod6",  
  6.         policy => policy.RequireAssertion(context =>  
  7.             context.User.HasClaim(c =>  
  8.             (c.Type == "IsHR" && Convert.ToBoolean(context.User.FindFirst(c2 => c2.Type == "IsHR").Value)) ||  
  9.             (c.Type == "DateOfJoining" && (DateTime.Now.Date - Convert.ToDateTime(context.User.FindFirst(c2 => c2.Type == "DateOfJoining").Value).Date).TotalDays >= 365))  
  10.             ));  
  11. });  
Can we Access request Context in Handlers?
 
The HandleRequirementAsync method contains two parameters, AuthorizationContext and Requirement. Some of the frameworks, such as MVC, are allowed to add any object to the Resource property of the AuthorizationContext to pass an extra information. This Resource property is specific to the framework, so we can cast context.Resource object to appropriate context and access the resources,
  1. var myContext = context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;  
  2.   
  3. if (myContext != null)  
  4. {  
  5.     // Examine MVC specific item.  
  6.     var controllerName = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)myContext.ActionDescriptor).ControllerName;  
  7. }  
Summary
 
Claim-based authorization allows us to validate the user based on other characteristics such as username, date of joining, employee, other information, etc. Probably it is not possible with another kind of authorization such as role-based authorization. The claim-based authorization can be achieved by the policy based authorization by using a pre-configured policy. We can either use pre-configured policies or can create a custom policy based on our requirement for authorization.
 
You can view or download the source code from the GitHub link here.