Sunday, 7 June 2020

How To Implement Authentication Using Identity Model In ASP.NET Core

In the recent new releases of .NET Framework, Microsoft provides a new authentication process or mechanism called ASP.NET Core Identity. ASP.NET Core Identity is basically a membership system that provides login functionality including user registration in any ASP.NET Core applications. This new authentication system is intended to replace the existing membership system of classic ASP.NET. This new authentication system is based on the OWIN (Open Web Interface for .NET) library. In this article, we will discuss the below topics – 
  • Overview of ASP.NET Identity
  • Benefits of ASP.NET Core Identity
  • Limitations of ASP.NET Identity
  • How to create an application using Identity Authentication in ASP.NET Core

OVERVIEW OF ASP.NET IDENTITY

 
In ASP.NET, developers normally use Forms Authentication or Windows Authentication along with Membership, Roles, and Profile features to maintain the security of their web application. But as the years passed, these techniques become inefficient to deal with the new changing requirement related to the web application security. Like today, most of the web sites provide us login authentication along with social site authentication like Facebook, Google, etc. Also, some applications or web sites provide a custom authentication mechanism like OAuth based authentication. ASP.NET membership techniques do not have any process to deals with this type of authentication requirement. Except this, there are also some other disadvantages of ASP.NET Membership techniques like rigid database structure, complex object model.
 
So, to overcome this situation, Microsoft introduced a new authentication technique called ASP.NET Identity. This authentication technique is basically based on the OWIN (Open Web Interface for .Net) Library. In ASP.NET Identity system, there is a total of six important parts available as related to the local user accounts. They are –
  1. User
  2. Role
  3. User Manager
  4. Role Manager
  5. Authentication Manager
  6. Entity Framework DBContent
User Objects is always representing the Login User information which contains user id, password, as well as, profile information of any user. In ASP.NET Identity, the IdentityUser class always is used to capture the basic authentication information related to the user. If we want to store any custom information like profile details etc., then we can create our own custom class which must be inherited from the IdentityUser as a base class.
 
Role Objects is representing user role objects. In ASP.NET Identity, the IdentityRole class is used to provide the information related to the user role.

User Manager is representing how to operate or manage the user information or account like create user accounts, remove user accounts, change the password, add a role to the user, remove a role from the user, etc. These types of user-related operation can be performed by using a user manager. In Asp.Net Identity, UserManager class can be used in this purpose. 
 
Role Manager is representing how to manage the roles related to the user. Using Role Manager, we can perform different role related operations like create a role, remove a role, etc. In ASP.NET Identity, the RoleManager class can be used for this purpose.
 
So, in the above discussion, all the classes related to users and roles. These classes do not perform any authentication operations. Actually, authenticating a user login or signing is totally depends on the Authentication Manager. In ASP.NET Identity, the IAuthenticationManager interface basically represents an authentication manager. 


Benefits of ASP.NET Core Identity

 
ASP.NET Core Identity has many advantages or benefits like following.
  1. ASP.NET Core Identity provides separation of storage. It means ASP.NET Core Identity provides a separate storing concept for identity information (like username, password) and code for security implementations (like password hashing, password validation, etc.).
  2. Most of the APIs in the ASP.NET Core Identity are asynchronous.
  3. In ASP.NET Core Identity, we can implement custom password hashing using UserManager APIs with the help of IPasswordHasher interface.
  4. ASP.NET Core Identity support any types of external login provider like facebook, google, etc. to authenticate the user details.
  5. Now, ASP.NET Core Identity implements Entity Framework to store the user information.

Drawbacks of ASP.NET Core Identity

 
In spite of the above benefits, ASP.NET Core Identity has some drawbacks like,
  1. In this system, if a user is authenticated, then we can retrieve the custom defined user properties in the claims collections of the ClaimsIdentity.
  2. There are no APIs to performing any custom based query.
  3. It does not support the systems which use Non-Entity Framework or use NoSql Databases. 

Create an application using Identity Authentication in ASP.NET Core

 
Step 1 
 
First, open Visual Studio 2017 and click File --> New --> Project.
 
Step 2

Select the Web Application project and click the OK button.
 
How To Implement Authentication Using Identity Model In ASP.NET Core
 
Step 3
 
Now, in the Project Template Dialog box, Select Web Application (Model-View-Controller) Project Template.
 
Step 4
 
After selecting the Project Template, click on the "Change Authentication" button.
 
How To Implement Authentication Using Identity Model In ASP.NET Core 
 
Step 5
 
In the "Change Authentication" box, Select the individual User Accounts options and then click the OK button.
 
Step 6
 
After the above step, Visual Studio creates projects with default templates.
 
Step 7
 
Now, open the appsettings.json file and provide the database name, database server name, and related credentials to establish the connection with the database.
  1. {  
  2.   "ConnectionStrings": {  
  3.     "DefaultConnection""Server=xxx;Database=DemoAuthentication;Trusted_Connection=True;MultipleActiveResultSets=true;user id=sa;password=xxxxxx;"  
  4.   },  
  5.   "Logging": {  
  6.     "LogLevel": {  
  7.       "Default""Warning"  
  8.     }  
  9.   },  
  10.   "AllowedHosts""*"  
  11. }  
Step 8
 
Now, open the Package Manager Console from the Tools menu and run the below commands one by one.
  1. add migration test1  
  2. update-database  
Step 9
 
After successfully running the above commands, go to the SQL Server and check that related database has been created.
 
How To Implement Authentication Using Identity Model In ASP.NET Core 
 
Step 10
 
Now, build and run the applications. After running the application in the browser, click on the "Sign In" button.
 
How To Implement Authentication Using Identity Model In ASP.NET Core 
 
Step 11
 
Since we do not have any login credential, we need to register first and then try to log in.
 
Step 12
 
For that, click on the link Register as a New User.
 
How To Implement Authentication Using Identity Model In ASP.NET Core 
 
Step 13
 
In the Registration form, provide a Username and Password to register.
 
Step 14
 
After successful registration, the application allows us to log into the application.
 
How To Implement Authentication Using Identity Model In ASP.NET Core 
Step 15
 
Now, return back to the SQL server and run a query to select records from the table dbo.AspNetUsers
 
Step 17
 
This Table contains the register user details as below.
 
How To Implement Authentication Using Identity Model In ASP.NET Core 

Scaffolding the Login (Shared Views)

 
Now, if we check in our existing project code, we do not find any Login or Register user UI. but when we check the views folder, we find there is a shared view called _LoginPartial.cshtml. Shared view file contains the link details related to the Login and Register User UI. Actually, in this application, log in and its related all the UIs used as a shared UI. So, it takes the reference of that application and uses it accordingly. I have already discussed the basic concept of shared view in my previous article. 
 
Now,  if we want to customize the Login Form, then we can be scaffolding the Login or any other forms. 
 
Step 1
 
First, select the Views folder and right click and Select Add --> New Scaffold Item
 
Step 2
 
In the Scaffold Dialog Box, Select the Identity Option and Click on Ok Button
 
How To Implement Authentication Using Identity Model In ASP.NET Core 
 
Step 3
 
Now, Identity Dialog Box appears when we can select any of the available files to override. We will Select Account\Login Form and Click on Add Button.
 
How To Implement Authentication Using Identity Model In ASP.NET Core 
Step 4
 
The Selected Identity Form is added under the Identity Folder in the Areas Section.
 
How To Implement Authentication Using Identity Model In ASP.NET Core 
 
Step 5
 
Now we can change some UI design for the Login Page as below
  1. @page  
  2. @model LoginModel  
  3.   
  4. @{  
  5.     ViewData["Title"] = "Log in";  
  6. }  
  7. <h1>@ViewData["Title"]</h1>  
  8. <div class="row">  
  9.     <div class="col-md-4">  
  10.         <section>  
  11.             <form id="account" method="post">  
  12.                 <h4>Existing User Login In</h4>  
  13.                 <hr />  
  14.                 <div asp-validation-summary="All" class="text-danger"></div>  
  15.                 <div class="form-group">  
  16.                     <label asp-for="Input.Email"></label>  
  17.                     <input asp-for="Input.Email" class="form-control" />  
  18.                     <span asp-validation-for="Input.Email" class="text-danger"></span>  
  19.                 </div>  
  20.                 <div class="form-group">  
  21.                     <label asp-for="Input.Password"></label>  
  22.                     <input asp-for="Input.Password" class="form-control" />  
  23.                     <span asp-validation-for="Input.Password" class="text-danger"></span>  
  24.                 </div>  
  25.                 <div class="form-group">  
  26.                     <div class="checkbox">  
  27.                         <label asp-for="Input.RememberMe">  
  28.                             <input asp-for="Input.RememberMe" />  
  29.                             @Html.DisplayNameFor(m => m.Input.RememberMe)  
  30.                         </label>  
  31.                     </div>  
  32.                 </div>  
  33.                 <div class="form-group">  
  34.                     <button type="submit" class="btn btn-primary">Log in</button>  
  35.                 </div>  
  36.                 <div class="form-group">  
  37.                     <p>  
  38.                         <a id="forgot-password" asp-page="./ForgotPassword">Forgot your password?</a>  
  39.                     </p>  
  40.                     <p>  
  41.                         <a asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Register as a new user</a>  
  42.                     </p>  
  43.                 </div>  
  44.             </form>  
  45.         </section>  
  46.     </div>  
  47. </div>  
  48.   
  49. @section Scripts {  
  50.     <partial name="_ValidationScriptsPartial" />  
  51. }  
Step 6
 
Now, we want to implement some password policy like
  • Password Length must be at least 8 characters
  • Password must contain alphanumeric fields
  • Password must contain 1 Unique Character
  • Application Default Timeout is 5 mins 
For adding the above functionality, we need to add the below code in the ConfigureService() in Startup.cs Files.
  1. public void ConfigureServices(IServiceCollection services)  
  2.         {  
  3.             services.Configure<CookiePolicyOptions>(options =>  
  4.             {  
  5.                 options.CheckConsentNeeded = context => true;  
  6.                 options.MinimumSameSitePolicy = SameSiteMode.None;  
  7.             });  
  8.   
  9.             services.AddDbContext<ApplicationDbContext>(options =>  
  10.                 options.UseSqlServer(  
  11.                     Configuration.GetConnectionString("DefaultConnection")));  
  12.   
  13.             services.AddDefaultIdentity<IdentityUser>()  
  14.                 .AddDefaultUI(UIFramework.Bootstrap4)  
  15.                 .AddEntityFrameworkStores<ApplicationDbContext>();  
  16.   
  17.   
  18.             services.Configure<IdentityOptions>(options =>  
  19.             {  
  20.                 // Password settings.  
  21.                 options.Password.RequireDigit = true;  
  22.                 options.Password.RequireLowercase = true;  
  23.                 options.Password.RequireNonAlphanumeric = true;  
  24.                 options.Password.RequireUppercase = true;  
  25.                 options.Password.RequiredLength = 8;  
  26.                 options.Password.RequiredUniqueChars = 1;  
  27.   
  28.                 // Lockout settings.  
  29.                 options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);  
  30.                 options.Lockout.MaxFailedAccessAttempts = 5;  
  31.                 options.Lockout.AllowedForNewUsers = true;  
  32.   
  33.                 // User settings.  
  34.                 options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+#";  
  35.                 options.User.RequireUniqueEmail = false;  
  36.             });  
  37.   
  38.             services.ConfigureApplicationCookie(options =>  
  39.             {  
  40.                 // Cookie settings  
  41.                 options.Cookie.HttpOnly = true;  
  42.                 options.ExpireTimeSpan = TimeSpan.FromMinutes(5);  
  43.                 options.LoginPath = "/Identity/Pages/Account/Login";  
  44.                 options.AccessDeniedPath = "/Identity/Account/AccessDenied";  
  45.                 options.SlidingExpiration = true;  
  46.             });  
  47.   
  48.             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);  
  49.         }  
Now, run the application and check the above setting while register a new user.

No comments:

Post a Comment