ASP.NET Core Identity

Step By Step Implementation Of Register, Login, and Logout.

Pritomsarkar
6 min readMay 7, 2021

Overview

ASP.NET Core Identity is a membership system. It allows us to create, read, update and delete user accounts. Supports account confirmation, authentication, authorization, password recovery, etc. It also supports external login providers like Microsoft, Facebook, Google, etc. I will discuss the external login providers in my upcoming article.

Prerequisites

I expect you to have knowledge of object-oriented programming concepts in C#. I assume you know .NET Core concepts especially the MVC pattern also.

To code along with me, you will have to install the .NET Core 2.2, as well as Visual Studio. You can also use another IDE instead of a visual studio. You can find a link to the Github repository end of this article.

1.Environment Setup

Open Visual Studio 2017. Create a project “Asp.Net Core Web Application(.Ne Core)” with an MVC pattern Template. You Can name this project whatever you want. Let’s get start.

=> Configure Asp.Net Core

public class ApplicationDbContext: IdentityDbContext{public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options){ }}

So first you have to connect your DB to your application properly. it’s a basic process of .NET Core. I assume that you can be done it. Your application DbContext class must inherit from IdentityDbContext class instead of DbContext class. This is required because IdentityDbContext provides all the DbSet properties needed to manage the identity tables in SQL Server. You will see all the tables that the asp.net core identity framework generates in just a bit.

services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>();

Now time to, Configure ASP.NET Core Identity Services. above code,AddIdentity() method adds the default identity system configuration for the specified user and role types.

IdentityUser class is provided by ASP.NET core and contains properties for UserName, PasswordHash, Email, etc. This is the class that is used by default by the ASP.NET Core Identity framework to manage registered users of your application. If you want to store additional information about the registered users like their Gender, City, etc. Create a custom class that derives from IdentityUser that’s it.

Similarly, IdentityRole is also a class provided by ASP.NET Core Identity and contains Role information.

//Clarify codeapp.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute("default", "{ controller=Home}/{action=Index}/{id?}");
});
}

You have to call UseAuthentication() method to add the Authentication middleware to the application’s request processing pipeline in your startup class.

The important point to keep in mind is must add authentication middleware before the MVC middleware in the request processing pipeline.

Now time to Migration and update the database process. from the Package Manager Console window execute the following command to add a new migration. This migration contains code that creates the tables required by the ASP.NET Core Identity system. Finally, execute the Update-Database command to apply the identity migration and have the required identity tables created.

Add-Migration AddIdentity
Update-Database
Identity Tables

2.Register new user

ViewModels/RegisterViewModel.cs

You will use this RegisterViewModel Class as the model for Register view. It actually carries the information from the view to the controller class.

Now I have to create a controller. you are dealing with a user account here, so we set name’s it AccountController.

public class AccountController : Controller
{
[HttpGet]
public IActionResult Register()
{
return View();}}

Also, you have to add some code to your master page.

<li class="nav-item ml-auto">   <a class="nav-link text-dark" asp-controller="account" asp-    action="register">           Register
</a>
</li>

Now if you run this application, you will find this output.

Output

If you click Register, you will find an error. that’s because at the moment within our AccountController we don’t have an Action method that can handle the Post issued by our register view.

3.UserManager and SignInManager

UserManager

UserManager<IdentityUser> class contains the required methods to manage users in the underlying data store. when we register a new user, then it will need.

SignInManager

SignInManager<IdentityUser> class contains the required methods for users to sign in.when you log in, then it will need.

Now we write code in the AccountController Post method of register Action.

Controller/AccountController

Now you successfully completed the register task.

Now if you run this application, then you show that you can successfully create a new account.

When you will click the register button then:-

Database

So your new user registration task is working!

4.Show or hide login and logout

Inject SignInManager in the Layout page, so we could check if the user Sign-in or not.

Now you have to write a code for the logout part in your AccountController.

[HttpPost]
public async Task<IActionResult> Logout()
{ await signInManager.SignOutAsync(); return RedirectToAction("index", "home");}

So you are already implementing the code of Register and Logout for our user.

Now time to Implementing login functionality.

5.Implementing login functionality

To implement the login functionality in your application, we need to implement the following

Login View Model

Login View

Login action methods in the AccountController

To log in to a user, we need their Email which is the username and password, and whether if they want a persistent cookie or session cookie.

A session cookie is created and stored within the session instance of the browser. A session cookie does not contain an expiration date and is permanently deleted when the browser window is closed.

A persistent cookie on the other hand is not deleted when the browser window is closed. It usually has an expiry date and deleted on the date of expiry.

LogIn Action In AccountController.

If you run your application, then you can do successfully register new users, also login and log out.

Login Page
After LogIn

If you Click Logout. then it will work as expected.

6.Redirect user to original URL after login.

By default, ASP.NET Core redirects to the login URL with the ReturnUrl query string parameter. The URL that we were trying to access will be the value of the ReturnUrl query string parameter.

So you have to add some code in your login action.

AccountController.

7.Conclusion

So you successfully created your task. now you can register, login, and log out a new user.

Hope you guys enjoy this article. You can download this application to my Github Repository.

Happy Coding :)

--

--

No responses yet