Authentication And Claim Based Authorization With ASP.NET Identity Core

Introduction

The authentication determines application identity while authorization determines what a subject may or may not do. The claim based identity is nothing but attaching the concept of claim to the identity. The claims are not what the subject can and cannot do. They are what the subject is or is not. It does the simple process of the authentication.

When an identity is created for authenticated user, it may be assigned one or more claims which are issued by trusted party. The claim is a name-value pair that represents what the subject is or is not, instead of what the subject can and cannot do. The claim based authorization checks the value of the claim and allows access to the resource, based on that value.

For example, a person is an Indian civilian and may have a voter id card issued by Election Commission of India. The voter id has his or her age on it. In this case, the claim name would be Age and this claim value would be an age of a person. For example, if the age is 18 on it, that means the person has authority to cast his/her vote.

A claim can contain multiple values and an identity can contain multiple claims of the same type.

The source code of this article is available at MSDN Sample.

Implement ASP.NET Core Identity

First, create an empty ASP.NET Core project. As this project doesn’t hold default implementation of ASP.NET Core Identity, we build an application step by step with ASP.NET Core Identity. We don’t have the default implementation of ASP.NET Core Identity so project.json file doesn't have any identity NuGet packages. Now, open the project.json file and modify it to add the dependencies and the tools, as per the code snippet given below. 

  1. {  
  2.   "dependencies": {  
  3.     "Microsoft.NETCore.App": {  
  4.       "version""1.1.0",  
  5.       "type""platform"  
  6.     },  
  7.     "Microsoft.AspNetCore.Razor.Tools": {  
  8.       "version""1.0.0-preview2-final",  
  9.       "type""build"  
  10.     },  
  11.     "Microsoft.EntityFrameworkCore.Tools": {  
  12.       "version""1.0.0-preview2-final",  
  13.       "type""build"  
  14.     },  
  15.     "BundlerMinifier.Core""2.2.306",  
  16.     "Microsoft.AspNetCore.Server.IISIntegration""1.1.0",  
  17.     "Microsoft.AspNetCore.Server.Kestrel""1.1.0",  
  18.     "Microsoft.AspNetCore.StaticFiles""1.1.0",  
  19.     "Microsoft.EntityFrameworkCore.SqlServer""1.1.0",  
  20.     "Microsoft.EntityFrameworkCore.SqlServer.Design""1.1.0",  
  21.     "Microsoft.Extensions.Configuration.EnvironmentVariables""1.1.0",  
  22.     "Microsoft.Extensions.Configuration.Json""1.1.0",  
  23.     "Microsoft.Extensions.Logging""1.1.0",  
  24.     "Microsoft.Extensions.Logging.Console""1.1.0",  
  25.     "Microsoft.Extensions.Logging.Debug""1.1.0",  
  26.     "Microsoft.Extensions.Options.ConfigurationExtensions""1.1.0",  
  27.     "Microsoft.VisualStudio.Web.BrowserLink.Loader""14.1.0",  
  28.     "Microsoft.AspNetCore.Authentication.Cookies""1.1.0",  
  29.     "Microsoft.AspNetCore.Diagnostics""1.1.0",  
  30.     "Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore""1.1.0",  
  31.     "Microsoft.AspNetCore.Identity.EntityFrameworkCore""1.1.0",  
  32.     "Microsoft.AspNetCore.Routing""1.1.0",  
  33.     "Microsoft.AspNetCore.Mvc""1.1.1"  
  34.   },  
  35.    
  36.   "tools": {  
  37.     "Microsoft.AspNetCore.Razor.Tools""1.0.0-preview2-final",  
  38.     "Microsoft.AspNetCore.Server.IISIntegration.Tools""1.0.0-preview2-final",  
  39.     "Microsoft.EntityFrameworkCore.Tools""1.0.0-preview2-final"  
  40.   },  
  41.    
  42.   "frameworks": {  
  43.     "netcoreapp1.1": {  
  44.       "imports": [  
  45.         "dotnet5.6",  
  46.         "portable-net45+win8"  
  47.       ]  
  48.     }  
  49.   },  
  50.   
  51.   "buildOptions": {  
  52.     "emitEntryPoint"true,  
  53.     "preserveCompilationContext"true  
  54.   },  
  55.    
  56.   "runtimeOptions": {  
  57.     "configProperties": {  
  58.       "System.GC.Server"true  
  59.     }  
  60.   },  
  61.    
  62.   "publishOptions": {  
  63.     "include": [  
  64.       "wwwroot",  
  65.       "**/*.cshtml",  
  66.       "appsettings.json",  
  67.       "web.config"  
  68.     ]  
  69.   },  
  70.    
  71.   "scripts": {  
  72.     "prepublish": [ "bower install""dotnet bundle" ],  
  73.     "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]  
  74.   }  
  75. }   

This file includes NuGet packages for both Entity Framework Core and ASP.NET Core Identity.

Now, create custom ApplicationUser class, which inherits IdentityUser class. This class holds the additional field for the identity user. The IdentityUser class holds user basic information such as Email, UserName, Password etc. The ApplicationUser class extends this class. It is used to store the user information. The code snippet is given below for the same. 

  1. using Microsoft.AspNetCore.Identity.EntityFrameworkCore;  
  2.   
  3. namespace ClaimApplication.Data  
  4. {  
  5.     public class ApplicationUser: IdentityUser  
  6.     {  
  7.         public string Name { get; set; }  
  8.     }  
  9. }   

To perform the database operations, we create an IdentityDbContext class named ApplicationDbContext, as per the code snippet given below. 

  1. using Microsoft.AspNetCore.Identity.EntityFrameworkCore;  
  2. using Microsoft.EntityFrameworkCore;  
  3.   
  4. namespace ClaimApplication.Data  
  5. {  
  6.     public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole, string>  
  7.     {  
  8.         public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)  
  9.         {  
  10.   
  11.         }  
  12.     }  
  13. }   

This class needs to know that which type Application user and role are dealing with the Application. We passed ApplicationUser and IdentityRole as a parameter, while creating the object of ApplicationDbContext class. Here, the third parameter represents the primary key data type for both IdentityUser and IdentityRole.

The application needs to configure to implement ASP.NET Core Identity. Now, add the identity in the method Configure of the Startup class. The code snippet is given below to add the identity in the Application.

  1. app.UseIdentity();   

As the concept of Dependency Injection is central to ASP.NET Core Application, we register context, identity and policy to Dependency Injection during the application start up. Thus, we register these as a Service in the ConfigureServices method of the StartUp class, as per the code snippet given below. 

  1. public void ConfigureServices(IServiceCollection services)  
  2.         {  
  3.             services.AddDbContext<ApplicationDbContext>(options =>  
  4.              options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  
  5.   
  6.             services.AddIdentity<ApplicationUser, IdentityRole>()  
  7.                 .AddEntityFrameworkStores<ApplicationDbContext>()  
  8.                 .AddDefaultTokenProviders();  
  9.             services.AddMvc();  
  10.             services.AddAuthorization(options =>  
  11.             {  
  12.                 options.AddPolicy("AddEditUser", policy => {  
  13.                     policy.RequireClaim("Add User""Add User");  
  14.                     policy.RequireClaim("Edit User""Edit User");  
  15.                     });                 
  16.                 options.AddPolicy("DeleteUser", policy => policy.RequireClaim("Delete User""Delete User"));  
  17.             });  
  18.         }   

As per the above code snippet, we need to build and register the policy. This takes places as part of the Authorization service configuration. The claims requirements are policy based. We create policy which can contain one and more than one claims. The authenticate user has these claims then he/she authorizes to access the resources. 

In this case the AddEditUser policy checks for the presence of an “Add User” and “Edit User” claims on the current identity.

Here, the DefaultConnection is the connection string, which is defined in appsettings.json file, as per the code snippet given below. 

  1. {  
  2.   "ConnectionStrings": {  
  3.     "DefaultConnection""Data Source=DESKTOP-RG33QHE;Initial Catalog=ClaimDb;User ID=sa; Password=****"  
  4.   },  
  5.   "Logging": {  
  6.     "IncludeScopes"false,  
  7.     "LogLevel": {  
  8.       "Default""Debug",  
  9.       "System""Information",  
  10.       "Microsoft""Information"  
  11.     }  
  12.   }  
  13. }   

Now, we have configured settings to create the database, so we have time to create a database, using migration. For database migration , we need to follow the following steps.

  1. Tools -> NuGet Package Manager -> Package Manager Console.
  2. Run PM> Add-Migration MyFirstMigration to scaffold a migration to create the initial set of tables for our model. If we receive an error which states the term `add-migration' is not recognized as the name of a cmdlet, then close and reopen Visual Studio.
  3. Run PM> Update-Database to apply the new migration to the database. Since our database doesn't exist yet, it will be created for us before the migration is applied.
Application Users

This section demonstrates that how to create, edit and delete the identity users and how to assign the claims to a user. There is UserManager, which exposes the user related APIs. This creates the user in the Application and is stored in the database.

Now Claim data create which be assigned to user. The following code snippet for some claim data. 

  1. using System.Collections.Generic;  
  2.   
  3. namespace ClaimApplication.Data  
  4. {  
  5.     public static class ClaimData  
  6.     {  
  7.         public static List<string> UserClaims { get; set; } = new List<string>  
  8.                                                             {  
  9.                                                                 "Add User",  
  10.                                                                 "Edit User",  
  11.                                                                 "Delete User"  
  12.                                                             };  
  13.     }  
  14. }   

Now, we proceed to the controller. We create controller named UserController under the Controllers folder of the application. It has all ActionResult methods for the end user interface of operations. We create  the UserManager instances. Subsequently, we inject it in the controller's constructor to get its object. The following is a partial code snippet for the UserController in which UserManager is injected, using constructor dependency Injection. 

  1. using Microsoft.AspNetCore.Mvc;  
  2. using Microsoft.AspNetCore.Mvc.Rendering;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Security.Claims;  
  7. using System.Threading.Tasks;  
  8.   
  9. namespace IdentitySampleApplication.Controllers  
  10. {  
  11.     [Authorize]  
  12.     public class UserController : Controller  
  13.     {  
  14.         private readonly UserManager<ApplicationUser> userManager;  
  15.   
  16.         public UserController(UserManager<ApplicationUser> userManager)  
  17.         {  
  18.             this.userManager = userManager;  
  19.         }  
  20.     }  
  21. }  

The AuthorizeAttribute attribute applied to the entire controller which means this controller access by authenticated users only.

We can notice that Controller takes UserManager as constructor parameter. ASP.NET Core Dependency Injection will take care of passing the instance of UserManager into UserController. The controller is developed to handle the operations requests for the application identity user. Now, let's develop the user interface for the user listing, add user, edit user and delete user. Let's see each one by one.

User List View

When we click on top User menu of the application, it shows the user listing, as shown in figure 1. The user data is displayed in a tabular format and on this view, it has linked to adding a new user, edit a user and delete a user.

To pass the data from the controller to view, create named UserListViewModel view model, as per the code snippet, mentioned below. This view model is used for the user listing. 

  1. namespace ClaimApplication.Models  
  2. {  
  3.     public class UserListViewModel  
  4.     {  
  5.         public string Id { get; set; }  
  6.         public string Name { get; set; }  
  7.         public string Email { get; set; }      
  8.     }  
  9. }   

Now, we create an action method, which returns an index view with the data. The code snippet of an Index action method in UserController is mentioned below. 

  1. [HttpGet]  
  2.         public IActionResult Index()  
  3.         {  
  4.             List<UserListViewModel> model = new List<UserListViewModel>();  
  5.             model = userManager.Users.Select(u => new UserListViewModel  
  6.             {  
  7.                 Id = u.Id,  
  8.                 Name = u.Name,  
  9.                 Email = u.Email  
  10.             }).ToList();  
  11.             return View(model);  
  12.         }   

Now, we create an index view, as per the code snippet, mentioned below under the User folder of the views. 

  1. @model IEnumerable<UserListViewModel>  
  2. @using ClaimApplication.Models  
  3. @using ClaimApplication.Code  
  4.   
  5. <div class="top-buffer"></div>  
  6. <div class="panel panel-primary">  
  7.     <div class="panel-heading panel-head">Users</div>  
  8.     <div class="panel-body">  
  9.         <div class="btn-group">  
  10.             <a id="createEditUserModal" data-toggle="modal" asp-action="AddUser" data-target="#modal-action-user" class="btn btn-primary">  
  11.                 <i class="glyphicon glyphicon-plus"></i>  Add User  
  12.             </a>  
  13.         </div>  
  14.         <div class="top-buffer"></div>  
  15.         <table class="table table-bordered table-striped table-condensed">  
  16.             <thead>  
  17.                 <tr>  
  18.                     <th>Name</th>  
  19.                     <th>Email</th>                     
  20.                     <th>Action</th>  
  21.                 </tr>  
  22.             </thead>  
  23.             <tbody>  
  24.                 @foreach (var item in Model)  
  25.                 {  
  26.                     <tr>  
  27.                         <td>@item.Name</td>  
  28.                         <td>@item.Email</td>                          
  29.                         <td>  
  30.                             <a id="editUserModal" data-toggle="modal" asp-action="EditUser" asp-route-id="@item.Id" data-target="#modal-action-user"  
  31.                                class="btn btn-info">  
  32.                                 <i class="glyphicon glyphicon-pencil"></i>  Edit  
  33.                             </a>  
  34.                             <a id="deleteUserModal" data-toggle="modal" asp-action="DeleteUser" asp-route-id="@item.Id" data-target="#modal-action-user" class="btn btn-danger">  
  35.                                 <i class="glyphicon glyphicon-trash"></i>  Delete  
  36.                             </a>  
  37.                         </td>  
  38.                     </tr>  
  39.                 }  
  40.             </tbody>  
  41.         </table>  
  42.     </div>  
  43. </div>  
  44.   
  45. @Html.Partial("_Modal"new BootstrapModel { ID = "modal-action-user", AreaLabeledId = "modal-action-user-label", Size = ModalSize.Medium })  
  46.   
  47. @section scripts  
  48. {  
  49.     <script src="~/js/user-index.js" asp-append-version="true"></script>  
  50. }   

It shows all the operational forms in the Bootstrap model popup, so create the user - index.js file, as per the code snippet given below. 

  1. (function ($) {  
  2.     function User() {  
  3.         var $this = this;  
  4.   
  5.         function initilizeModel() {  
  6.             $("#modal-action-user").on('loaded.bs.modal'function (e) {  
  7.   
  8.             }).on('hidden.bs.modal'function (e) {  
  9.                 $(this).removeData('bs.modal');  
  10.             });  
  11.         }  
  12.         $this.init = function () {  
  13.             initilizeModel();  
  14.         }  
  15.     }  
  16.     $(function () {  
  17.         var self = new User();  
  18.         self.init();  
  19.     })  
  20. }(jQuery))   

When the Application runs and calls the index() action method from UserController with a HttpGet request, it gets all the users, which are listed in the UI, as shown in Figure 1.


Figure 1: Application User Listing

Add User

To pass the data from UI to a controller to add a user, it uses view model named UserViewModel. The code snippet is given below for the same. 

  1. using Microsoft.AspNetCore.Mvc.Rendering;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4.   
  5. namespace ClaimApplication.Models  
  6. {  
  7.     public class UserViewModel  
  8.     {  
  9.         public string Id { get; set; }  
  10.         public string UserName { get; set; }  
  11.         [DataType(DataType.Password)]  
  12.         public string Password { get; set; }  
  13.         [Display(Name="Confirm Password")]  
  14.         [DataType(DataType.Password)]  
  15.         public string ConfirmPassword { get; set; }  
  16.         public string Name { get; set; }  
  17.         public string Email { get; set; }  
  18.         [Display(Name = "User Claims")]  
  19.         public List<SelectListItem> UserClaims { get; set; }     
  20.     }  
  21. }   

The UserController has an action method, which is named as AddUser, which returns the view to add a user. The code snippet mentioned below is for same action method for both GET and Post requests. 

  1. [Authorize(Policy = "AddEditUser")]  
  2.         [HttpGet]  
  3.         public IActionResult AddUser()  
  4.         {  
  5.             UserViewModel model = new UserViewModel();  
  6.             model.UserClaims = ClaimData.UserClaims.Select(c => new SelectListItem  
  7.             {  
  8.                 Text = c,  
  9.                 Value = c  
  10.             }).ToList();  
  11.             return PartialView("_AddUser", model);  
  12.         }  
  13.   
  14.         [HttpPost]  
  15.         public async Task<IActionResult> AddUser(UserViewModel model)  
  16.         {  
  17.             if (ModelState.IsValid)  
  18.             {  
  19.                 ApplicationUser user = new ApplicationUser  
  20.                 {  
  21.                     Name = model.Name,  
  22.                     UserName = model.UserName,  
  23.                     Email = model.Email  
  24.                 };  
  25.                 List<SelectListItem> userClaims = model.UserClaims.Where(c => c.Selected).ToList();  
  26.                 foreach (var claim in userClaims)  
  27.                 {  
  28.                     user.Claims.Add(new IdentityUserClaim<string>  
  29.                     {  
  30.                         ClaimType = claim.Value,  
  31.                         ClaimValue = claim.Value  
  32.                     });  
  33.                 }  
  34.   
  35.                 IdentityResult result = await userManager.CreateAsync(user, model.Password);  
  36.                 if (result.Succeeded)  
  37.                 {  
  38.                     return RedirectToAction("Index");  
  39.                 }  
  40.             }  
  41.             return View(model);  
  42.         }   

As per above code snippet AddEditUser policy applied using the Policy property on the AuthorizeAttribute attribute to specify the policy name; in this instance only identities matching the policy will be allowed access to AddUserAction on the controller.

If we have a controller that is protected by the AuthorizeAttribute attribute, but want to allow anonymous access to particular actions we apply the AllowAnonymousAttribute attribute;

The CreateAsync asynchronous method of the UserManager class performs operation to creates new user in the Application. This method has new ApplicationUser as a parameter.

The GET request for the AddUser action method returns _AddUser partial view; the code snippet follows under the User folder of views. 

  1. @model UserViewModel  
  2. @using ClaimApplication.Models  
  3.   
  4. <form asp-action="AddUser" role="form">  
  5.     @await Html.PartialAsync("_ModalHeader"new ModalHeader { Heading = "Add User" })  
  6.     <div class="modal-body form-horizontal">  
  7.         <div class="row">              
  8.                 <div class="form-group">  
  9.                     <label asp-for="Name" class="col-lg-3 col-sm-3 control-label"></label>  
  10.                     <div class="col-lg-6">  
  11.                         <input asp-for="Name" class="form-control" />  
  12.                     </div>  
  13.                 </div>  
  14.                 <div class="form-group">  
  15.                     <label asp-for="Email" class="col-lg-3 col-sm-3 control-label"></label>  
  16.                     <div class="col-lg-6">  
  17.                         <input asp-for="Email" class="form-control" />  
  18.                     </div>  
  19.                 </div>  
  20.                 <div class="form-group">  
  21.                     <label asp-for="UserClaims" class="col-lg-3 col-sm-3 control-label"></label>  
  22.                     <div class="col-lg-9">  
  23.                         @for(int i =0; i< Model.UserClaims.Count;i++)  
  24.                         {  
  25.                             <div class="col-lg-4">  
  26.                                 <input type="checkbox" asp-for="@Model.UserClaims[i].Selected" />  
  27.                                 <label asp-for="@Model.UserClaims[i].Selected">@Model.UserClaims[i].Text</label>  
  28.                                 <input type="hidden" asp-for="@Model.UserClaims[i].Value" />  
  29.                                 <input type="hidden" asp-for="@Model.UserClaims[i].Text" />  
  30.                             </div>  
  31.                         }  
  32.                     </div>  
  33.                 </div>                  
  34.                     <div class="form-group">  
  35.                         <label asp-for="UserName" class="col-lg-3 col-sm-3 control-label"></label>  
  36.                         <div class="col-lg-6">  
  37.                             <input asp-for="UserName" class="form-control" />  
  38.                         </div>  
  39.                     </div>  
  40.                     <div class="form-group">  
  41.                         <label asp-for="Password" class="col-lg-3 col-sm-3 control-label"></label>  
  42.                         <div class="col-lg-6">  
  43.                             <input asp-for="Password" class="form-control" />  
  44.                         </div>  
  45.                     </div>  
  46.                     <div class="form-group">  
  47.                         <label asp-for="ConfirmPassword" class="col-lg-3 col-sm-3 control-label"></label>  
  48.                         <div class="col-lg-6">  
  49.                             <input asp-for="ConfirmPassword" class="form-control" />  
  50.                         </div>  
  51.                     </div>  
  52.                 </div>  
  53.             </div>          
  54.         @await Html.PartialAsync("_ModalFooter"new ModalFooter { })  
  55. </form>   

When the Application runs and we click on the Add User button, it makes a GET request for the AddUser() action; add a user screen, as shown in Figure 2.


Figure 2: Add User

Edit User

To pass the data from UI to the controller to edit a user, use view model named EditUserViewModel. The following code snippet for EditUserViewModel. 

  1. using Microsoft.AspNetCore.Mvc.Rendering;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4.   
  5. namespace ClaimApplication.Models  
  6. {  
  7.     public class EditUserViewModel  
  8.     {  
  9.         public string Id { get; set; }  
  10.         public string Name { get; set; }  
  11.         public string Email { get; set; }        
  12.         [Display(Name = "User Claims")]  
  13.         public List<SelectListItem> UserClaims { get; set; }  
  14.     }  
  15. }   

The UserController has an action method named EditUser, which returns the view to edit a user. The code snippet mentioned below is for the same action method for both GET and Post requests. 

  1. [Authorize(Policy = "AddEditUser")]  
  2.         [HttpGet]  
  3.         public async Task<IActionResult> EditUser(string id)  
  4.         {  
  5.             EditUserViewModel model = new EditUserViewModel();  
  6.   
  7.             if (!String.IsNullOrEmpty(id))  
  8.             {  
  9.                 ApplicationUser applicationUser = await userManager.FindByIdAsync(id);  
  10.                 if (applicationUser != null)  
  11.                 {  
  12.                     model.Name = applicationUser.Name;  
  13.                     model.Email = applicationUser.Email;  
  14.                     var claims = await userManager.GetClaimsAsync(applicationUser);  
  15.                     model.UserClaims = ClaimData.UserClaims.Select(c => new SelectListItem  
  16.                     {  
  17.                         Text = c,  
  18.                         Value = c,  
  19.                         Selected = claims.Any(x => x.Value == c)  
  20.                     }).ToList();  
  21.                 }  
  22.                 else  
  23.                 {  
  24.                     model.UserClaims = ClaimData.UserClaims.Select(c => new SelectListItem  
  25.                     {  
  26.                         Text = c,  
  27.                         Value = c  
  28.                     }).ToList();  
  29.                 }  
  30.   
  31.             }  
  32.             return PartialView("_EditUser", model);  
  33.         }  
  34.   
  35.         [HttpPost]  
  36.         public async Task<IActionResult> EditUser(string id, EditUserViewModel model)  
  37.         {  
  38.             if (ModelState.IsValid)  
  39.             {  
  40.                 ApplicationUser applicationUser = await userManager.FindByIdAsync(id);  
  41.                 if (applicationUser != null)  
  42.                 {  
  43.                     applicationUser.Name = model.Name;  
  44.                     applicationUser.Email = model.Email;  
  45.                     var claims = await userManager.GetClaimsAsync(applicationUser);  
  46.                     List<SelectListItem> userClaims = model.UserClaims.Where(c => c.Selected && claims.Any(u => u.Value != c.Value)).ToList();  
  47.                     foreach (var claim in userClaims)  
  48.                     {  
  49.                         applicationUser.Claims.Add(new IdentityUserClaim<string>  
  50.                         {  
  51.                             ClaimType = claim.Value,  
  52.                             ClaimValue = claim.Value  
  53.                         });  
  54.                     }  
  55.                     IdentityResult result = await userManager.UpdateAsync(applicationUser);  
  56.                     List<Claim> userRemoveClaims = claims.Where(c => model.UserClaims.Any(u => u.Value == c.Value && !u.Selected)).ToList();  
  57.                     foreach (Claim claim in userRemoveClaims)  
  58.                     {  
  59.                         await userManager.RemoveClaimAsync(applicationUser, claim);  
  60.                     }  
  61.                     if (result.Succeeded)  
  62.                     {  
  63.                         return RedirectToAction("Index");  
  64.                     }  
  65.                 }  
  66.             }  
  67.             return PartialView("_EditUser", model);  
  68.         }   

There are four asynchronous methods, which are used of the UserManager class, which performs an action, as shown below.

  • FindByIdAsync
    This method has an Application user Id as a parameter and returns already existing user, which is based on the input.

  • GetClaimsAsync
    This method asynchronously returns the claims for a user.

  • UpdateAsync
    This method has an existing ApplicationUser as a parameter and updates that user in the Application.

  • RemoveClaimAsync
    This method has two parameters, where one is an existing Application user and another is assigned claim. This method asynchronously removes a claim from a user.

The GET request for the EditUser action method returns _EditUser partial view; the code snippet follows under the User folder of views.

  1. @model EditUserViewModel  
  2. @using ClaimApplication.Models  
  3.   
  4. <form asp-action="EditUser" role="form">  
  5.     @await Html.PartialAsync("_ModalHeader"new ModalHeader { Heading = "Edit User" })  
  6.     <div class="modal-body form-horizontal">  
  7.         <div class="row">              
  8.             <div class="form-group">  
  9.                 <label asp-for="Name" class="col-lg-3 col-sm-3 control-label"></label>  
  10.                 <div class="col-lg-6">  
  11.                     <input asp-for="Name" class="form-control" />  
  12.                 </div>  
  13.             </div>              
  14.             <div class="form-group">  
  15.                 <label asp-for="Email" class="col-lg-3 col-sm-3 control-label"></label>  
  16.                 <div class="col-lg-6">  
  17.                     <input asp-for="Email" class="form-control" />  
  18.                 </div>  
  19.             </div>  
  20.   
  21.             <div class="form-group">  
  22.                 <label asp-for="UserClaims" class="col-lg-3 col-sm-3 control-label"></label>  
  23.                 <div class="col-lg-9">  
  24.                     @for (int i = 0; i < Model.UserClaims.Count; i++)  
  25.                     {  
  26.                         <div class="col-lg-4">  
  27.                             <input type="checkbox" asp-for="@Model.UserClaims[i].Selected" />  
  28.                             <label asp-for="@Model.UserClaims[i].Selected">@Model.UserClaims[i].Text</label>  
  29.                             <input type="hidden" asp-for="@Model.UserClaims[i].Value" />  
  30.                             <input type="hidden" asp-for="@Model.UserClaims[i].Text" />  
  31.                         </div>  
  32.                     }  
  33.                 </div>  
  34.                </div>  
  35.             </div>  
  36.     </div>  
  37.     @await Html.PartialAsync("_ModalFooter"new ModalFooter { })  
  38. </form>  

When the Application runs and you click on the Edit button in the User listing, it makes a GET request for the EditUser() action, followed by editing the user screen, which is shown in Figure 3.


Figure 3: Edit User

Delete User

The UserController has an action method named DeleteUser, which returns the view to delete a user. The code snippet mentioned below is for the same action method for both GET and Post requests. 

  1. [Authorize(Policy = "DeleteUser")]  
  2.       [HttpGet]  
  3.       public async Task<IActionResult> DeleteUser(string id)  
  4.       {  
  5.           string name = string.Empty;  
  6.           if (!String.IsNullOrEmpty(id))  
  7.           {  
  8.               ApplicationUser applicationUser = await userManager.FindByIdAsync(id);  
  9.               if (applicationUser != null)  
  10.               {  
  11.                   name = applicationUser.Name;  
  12.               }  
  13.           }  
  14.           return PartialView("_DeleteUser", name);  
  15.       }  
  16.   
  17.       [HttpPost]  
  18.       public async Task<IActionResult> DeleteUser(string id, IFormCollection form)  
  19.       {  
  20.           if (!String.IsNullOrEmpty(id))  
  21.           {  
  22.               ApplicationUser applicationUser = await userManager.FindByIdAsync(id);  
  23.               if (applicationUser != null)  
  24.               {  
  25.                   IdentityResult result = await userManager.DeleteAsync(applicationUser);  
  26.                   if (result.Succeeded)  
  27.                   {  
  28.                       return RedirectToAction("Index");  
  29.                   }  
  30.               }  
  31.           }  
  32.           return View();  
  33.       }   

Here, DeleteAsync method of UserManager is used, which takes an existing Application user as an input parameter. It deletes an existing Application user.

The AuthoriseAttribute attribute with policy name “DeleteUser” represents that it be accessed by only those user who have claims for this policy.

The GET request for the DeleteUser action method returns _DeleteUser partial View. The code snippet mentioned below is under the User folder of Views. 

  1. @model string  
  2. @using ClaimApplication.Models  
  3.   
  4. <form asp-action="DeleteUser" role="form">  
  5.     @Html.Partial("_ModalHeader"new ModalHeader { Heading = "Delete User" })  
  6.   
  7.     <div class="modal-body form-horizontal">  
  8.         Are you want to delete @Model?  
  9.     </div>  
  10.     @Html.Partial("_ModalFooter"new ModalFooter { SubmitButtonText = "Delete" })  
  11. </form>   

When the Application runs and a user clicks on the "Delete" button in the user listing, it makes a GET request for the DeleteUser() action, then the delete user screen is shown below.


Figure 4: Delete User

Authetication and Authorisation

This section demonstrates the login and logout functionality of the application. As the Application users already exist in the system, to implement login and logout functionality, create AccountController under the Controllers folder. This controller holds both login and logout action methods. We create SignInManager instance. Now, we inject it in the controller's constructor to get its object. The following is a partial code snippet for the AccountController in which SignInManager is injected, using constructor Dependency Injection. 

  1. using ClaimApplication.Data;  
  2. using ClaimApplication.Models;  
  3. using Microsoft.AspNetCore.Authorization;  
  4. using Microsoft.AspNetCore.Identity;  
  5. using Microsoft.AspNetCore.Mvc;  
  6. using System.Threading.Tasks;  
  7.   
  8.   
  9. namespace ClaimApplication.Controllers  
  10. {  
  11.     public class AccountController : Controller  
  12.     {  
  13.         private readonly SignInManager<ApplicationUser> signInManager;  
  14.   
  15.         public AccountController(SignInManager<ApplicationUser> signInManager)  
  16.         {  
  17.             this.signInManager = signInManager;  
  18.         }  
  19.     }  
  20. }   

The SignInManager manages the sign operations for users.

Login

To pass the data from UI to a controller to login an application user, it uses view model named LoginViewModel. The code snippet is given below for the same. 

  1. using System.ComponentModel.DataAnnotations;  
  2.   
  3. namespace ClaimApplication.Models  
  4. {  
  5.     public class LoginViewModel  
  6.     {  
  7.         [Required]  
  8.         public string UserName { get; set; }  
  9.         [Required]  
  10.         [DataType(DataType.Password)]  
  11.         public string Password { get; set; }  
  12.         [Display(Name = "Remember me?")]  
  13.         public bool RememberMe { get; set; }  
  14.     }  
  15. }   

The AccountController has two action methods, where one is for GET request named Login, which returns the view to login and another has same name. It also handles POST request to login an Application user. The code snippet mentioned below is for same action method for both GET and Post requests. 

  1. public IActionResult Login(string returnUrl = null)  
  2.         {  
  3.             ViewData["ReturnUrl"] = returnUrl;  
  4.             return View();  
  5.         }  
  6.   
  7.         [HttpPost]  
  8.         [AllowAnonymous]  
  9.         [ValidateAntiForgeryToken]  
  10.         public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)  
  11.         {  
  12.             ViewData["ReturnUrl"] = returnUrl;  
  13.             if (ModelState.IsValid)  
  14.             {                  
  15.                 var result = await signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);  
  16.                 if (result.Succeeded)  
  17.                 {                     
  18.                     return RedirectToLocal(returnUrl);  
  19.                 }                 
  20.                 else  
  21.                 {  
  22.                     ModelState.AddModelError(string.Empty, "Invalid login attempt.");  
  23.                     return View(model);  
  24.                 }  
  25.             }             
  26.             return View(model);  
  27.         }  
  28.         private IActionResult RedirectToLocal(string returnUrl)  
  29.         {  
  30.             if (Url.IsLocalUrl(returnUrl))  
  31.             {  
  32.                 return Redirect(returnUrl);  
  33.             }  
  34.             else  
  35.             {  
  36.                 return RedirectToAction(nameof(HomeController.Index), "Home");  
  37.             }  
  38.         }   

Here the Login action method has a parameter named returnUrl, which represents that a user is redirected on a page after login. Suppose an end user is not authenticated and he tries to access the internal page via URL, then this internal page URL is stored in this parameter and the user is redirected on the login screen. Afterwards, the user authenticates from the login screen, followed by redirecting on that URL page rather than a regular redirection.

The SignInManager class exposes API methods, which is used to manage sign in operations. There is an asynchronous method, which is PasswordSignInAsync. This method takes the username and password of a user as inputs and checks its validity and issues the application cookie, if they are correct.

The GET request for the Login action method returns Login view and the code snippet follows under the Account folder of views. 

  1. @model LoginViewModel  
  2. @using ClaimApplication.Models  
  3.   
  4. <div class="row">  
  5.     <div class="col-md-3"></div>  
  6.     <div class="col-md-6">  
  7.         <div class="top-buffer"></div>  
  8.         <div class="panel panel-primary">  
  9.             <div class="panel-heading">Login</div>  
  10.             <div class="panel-body">  
  11.                 <section>  
  12.                     <form asp-controller="Account" asp-action="Login" asp-route-returnurl="@ViewData["ReturnUrl"]" method="post" class="form-horizontal">  
  13.                         <h4>Use a local account to log in.</h4>  
  14.                         <hr />  
  15.                         <div asp-validation-summary="All" class="text-danger"></div>  
  16.                         <div class="form-group">  
  17.                             <label asp-for="UserName" class="col-md-2 control-label"></label>  
  18.                             <div class="col-md-10">  
  19.                                 <input asp-for="UserName" class="form-control" />  
  20.                                 <span asp-validation-for="UserName" class="text-danger"></span>  
  21.                             </div>  
  22.                         </div>  
  23.                         <div class="form-group">  
  24.                             <label asp-for="Password" class="col-md-2 control-label"></label>  
  25.                             <div class="col-md-10">  
  26.                                 <input asp-for="Password" class="form-control" />  
  27.                                 <span asp-validation-for="Password" class="text-danger"></span>  
  28.                             </div>  
  29.                         </div>  
  30.                         <div class="form-group">  
  31.                             <div class="col-md-offset-2 col-md-10">  
  32.                                 <div class="checkbox">  
  33.                                     <label asp-for="RememberMe">  
  34.                                         <input asp-for="RememberMe" />  
  35.                                         @Html.DisplayNameFor(m => m.RememberMe)  
  36.                                     </label>  
  37.                                 </div>  
  38.                             </div>  
  39.                         </div>  
  40.                         <div class="form-group">  
  41.                             <div class="col-md-offset-2 col-md-10">  
  42.                                 <button type="submit" class="btn btn-primary">Log in</button>  
  43.                             </div>  
  44.                         </div>  
  45.                     </form>  
  46.                 </section>  
  47.             </div>  
  48.         </div>  
  49.     </div>  
  50.     <div class="col-md-3"></div>  
  51.     </div>   

When the Application runs and you click on the LogIn button, it makes a GET request for the Login() action and shows the login screen, as shown in Figure 5.


Figure 5: Login

The Application has a HomeController, which is accessed after successful authentication. It holds an action method named Index, which returns a view by authenticating the username. 

  1. using ClaimApplication.Data;  
  2. using Microsoft.AspNetCore.Authorization;  
  3. using Microsoft.AspNetCore.Identity;  
  4. using Microsoft.AspNetCore.Mvc;  
  5.   
  6. namespace ClaimApplication.Controllers  
  7. {  
  8.     public class HomeController : Controller  
  9.     {  
  10.         private readonly UserManager<ApplicationUser> userManager;  
  11.   
  12.         public HomeController(UserManager<ApplicationUser> userManager)  
  13.         {  
  14.             this.userManager = userManager;  
  15.         }  
  16.         [Authorize]  
  17.         public IActionResult Index()  
  18.         {  
  19.             string userName = userManager.GetUserName(User);  
  20.             return View("Index", userName);  
  21.         }  
  22.     }  
  23. }   

Here, Authorize attribute is used on the controller level, which means that this controller is accessed by only authenticate users. The action method has also used Authorize attribute, which represents that authenticated user can access this action method.

The GetUserName method of UserManager returns the authenticate user’s username, which is based on the user.

The authorized GET request for the Index action method returns an Index view. The code snippet follows under the Home folder of views. 

  1. @model string  
  2. <h1> Welcome @Model</h1>   

The Application has a partial view, which is used to show following details on the top header. If the user is not authenticated, it shows Log In button on top. If the user is authenticated, it shows the username and Log Off button. 

  1. @using Microsoft.AspNetCore.Identity  
  2. @using ClaimApplication.Models  
  3. @using ClaimApplication.Data  
  4.   
  5. @inject SignInManager<ApplicationUser> SignInManager  
  6. @inject UserManager<ApplicationUser> UserManager  
  7.   
  8. @if (SignInManager.IsSignedIn(User))  
  9. {  
  10.     <form asp-area="" asp-controller="Account" asp-action="SignOff" method="post" id="logoutForm" class="navbar-right">  
  11.         <ul class="nav navbar-nav navbar-right">  
  12.             <li>  
  13.                 <a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>  
  14.             </li>  
  15.             <li>  
  16.                 <button type="submit" class="btn btn-link navbar-btn navbar-link">Log off</button>  
  17.             </li>  
  18.         </ul>  
  19.     </form>  
  20. }  
  21. else  
  22. {  
  23.     <ul class="nav navbar-nav navbar-right">        
  24.         <li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>  
  25.     </ul>  
  26. }   

As per the code snippet is given above, the view has Injected Dependecy on its level and created instances of both SignInManager and UserManager. The IsSignedIn method of SignInManager class checks wheather a user login or not in the application.

Now, we login with the valid credentials of a user, followed by redirecting on the Index action method of HomeController. The Index view shows as shown in Figure 6.


Figure 6: Welcome screen

Claim Based Authorisation

As we created two policies based on the claims in this application, the AddEditUser policy contains two claims one is “Add User” and another is “Edit User”. The DeleteUser policy conatins “Delete User” claim. We used these policies on the action method of UserController controller. If a user doesn’t have one of the claims which includes in AddEditUser policy then autheticate user doesn’t authorize accessing that action method on which policy has been implemented.

Now, we login with valid credentials of a user while that user doesn’t have “Delete User” claim as well then it redirects on the AccessDenied action method of AccountController controller. 

  1. public IActionResult AccessDenied()  
  2.         {  
  3.             return View();  
  4.         }      

The AccessDenied action method returns AccessDenied view, which has the code snippet given below. 

  1. <div class="row">  
  2.     <div class="col-md-3"></div>  
  3.     <div class="col-md-6">  
  4.         <div class="top-buffer"></div>  
  5.         <div class="panel panel-danger">  
  6.             <div class="panel-heading">Access Denied</div>  
  7.             <div class="panel-body">  
  8.                 <section>  
  9.                     <h1 class="text-danger">403 ! Access Denied</h1>  
  10.                     <br />  
  11.                     <a href="javascript:void(0)" onClick="backAway()" class="btn btn-success">Back</a>  
  12.                 </section>  
  13.             </div>  
  14.         </div>  
  15.     </div>  
  16.     <div class="col-md-3"></div>  
  17. </div>  
  18.   
  19. @section scripts  
  20. {  
  21.     <script>  
  22.         function backAway() {  
  23.             if (history.length === 1) {  
  24.                 window.location = "http://localhost:50841/"  
  25.             } else {  
  26.                 history.back();  
  27.             }  
  28.         }  
  29.     </script>  
  30. }   

Now, run the Application and login with the valid credentials. Its authentication is successful. This authenticates the user who doesn’t have ‘Delete User’ claim. We click on Delete button on user listing and it is being redirected on access denied because user doesn’t have ‘Delete User’ claim. The screen given below shows in case of access denial.


Figure 7: Unauthorised screen

As the application action methods call via ajax request so unauthorized user is being redirected on access denied using following code snippet on _Layout.cshtml. 

  1. <script type="text/javascript">  
  2.         $(function () {  
  3.             $(document).ajaxError(function (xhr, props) {                 
  4.                 if (props.status == 403) {  
  5.                    window.location = "http://localhost:49957/Account/AccessDenied";  
  6.                 } else if (props.status == 401) {  
  7.                     window.location = "http://localhost:49957/Account/Login";  
  8.                 }  
  9.             });  
  10.     });  
  11.     </script>   
Logout

Now, create an action method for Logout in AccountController, as per the code snippet given below. 

  1. [HttpPost]  
  2.         [ValidateAntiForgeryToken]  
  3.         public async Task<IActionResult> SignOff()  
  4.         {  
  5.             await signInManager.SignOutAsync();             
  6.             return RedirectToAction("Login");  
  7.         }   

This SignOutAsync clears the user claims, which are stored in cookies. This action method calls, when we click on Logout button, which is placed at the top.

Conclusion

This article introduced the authentication and authorization in ASP.NET Core with ASP.NET Core Identity, using Entity Framework Core with the "code first" development approach. It explained the claim based authorization in the Application. We used Bootstrap, CSS and JavaScript for the user interface design in this Application.

Downloads

You can download the complete source code from the MSDN Sample, using the links, mentioned below.

  1. Rating Star Application in ASP.NET Core
  2. CRUD Operations in ASP.NET Core and Entity Framework Core
  3. Repository Pattern In ASP.NET Core
  4. Generic Repository Pattern in ASP.NET Core
  5. Onion Architecture In ASP.NET Core MVC
  6. NET Core MVC: Authentication and Role Based Authorisation with Identity
  7. NET Core MVC: Authentication and Claim Based authorization with Identity

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now