ASP.NET Core Identity: Registration, Login and Logout
Tags: aspnetcore, identity, authentication, authorization
Published: 2022-10-08 20:42:42

---
title: ASP.NET Core Identity: Registration, Login and Logout
published: true
description: 
tags: aspnetcore, identity, authentication, authorization 
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---
####Introduction
In this blog post we will look into how to implement ASP.NET Core Identity in a web app for adding authentication and authorization feature. Users can create an account and login with a username and password. This article is especially focusing on newcomers and anyone new wants to learn or thinking of using Identity in their .NET program. This is a series of blog post so please look into other for more information.

####What is ASP.NET Core Identity?
When we build an application one of the key factors is that "how to handle the user management?", that means manages users, login, logout, passwords, profile data, roles, claims, tokens, email confirmation and more. So, to help ease these user management process we can use ASP.NET Core Identity a membership system.

####Development Setup
For this example, we will be creating a ASP.NET Core MVC Web App using Visual Studio 2022 and .NET 6.0

**Step 01:** When creating an ASP.NET Core Web App (MVC) we will not select the Authentication type and set it as "None" as we will be looking from scratch how to set up the Identity feature in the application. For simplicity we will uncheck the "Configure for HTTPS" and "Enable Docker"

![Create Project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gn1az87qsf09wduam42y.png)

After creating we will have a basing MVC web application without any authentication feature.

![Uncheck Authentication](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l2gevl4s1apw41tqhwgg.png)

And running the project will show the following webpage:

![Default Webpage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n79pwya4s73i075y6cqc.png)

**Step 02:** Now we will add Identity feature by Scaffolding. So, right click on the project and go to "ADD" and select "New Scaffolded Item". In the following window select "Identity" and press "Add". In order to scaffolded to run a nuget package "Microsoft.VisualStudio.Web.CodeGeneration.Design" need to install. This will get automatically install when adding scaffolded item.

![Scaffolding](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x9mozv2pttwk8fq7jpi8.png)

![options](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jh2s5tixxv24di27oovf.png)

From the following select the Identity features that we would like to add in our web app. For this example, we will be selecting "Login", "Logout", "Register". We also need to specify the following:
* Layout page: a layout page for the identity files so, we will be selecting our existing shared "_Layout.cshtml" page that got created by default with the project.
* Data Context Class: By selecting + button it will generate the context class name and we will rename it to "AspNetCoreIdentityDbContext"
* User class: By selecting + button we are setting the user model class name to "AspNetCoreIdentityUser"

![Identity select](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/434g1ks1wugru6ihg5ph.png)

Click on "Add" now our identity scaffolded. And we have the following structure changes in the project

![project structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f5sroyqo9ynec8r6gmhc.png)

Here we have "AspNetCoreIdentityDbContext" for our database. By which we will access our SQL Server. Then we have "AspNetCoreIdentityUser" which inherits from "IdentityUser" which implements the code for Login, Logout, Register and more. Now run the app and we need to add "Register" "Login" 

![model class](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0kvkkmjtjshrubmxeqnn.png)

To add this go to the header section in "_Layout.cshtml" under "Views" -> "Shared" and made the following changes.

![default page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iuj1dm1kt5uy7w52yoav.png)

![Regisyer Login](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0mksavc90vd4cyvmj8cs.png)

But wait clicking "Register" and "Login" link does not work. This is because Identity is implemented in ASP.Net Core MVC is with "Razor" pages. So, we have an MVC application which needs Ragpr page supports and for this we have to inject our program with razor page support by adding "app.MapRazorPages();" in the Program.cs

![exception](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fqmp4oqrioo6abflks4r.png)

Now clicking Register and Login button redirects to the respective pages.

![exception page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1vwr6wql6j8fq0d7iwqy.png)

![login page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w4qz7hus04u2t5dy3934.png)

**Step 03:** By default in Register page Identity adds only Email, Password and confirm passowrd fields. But we will add "First Name" and "Last Name" field. To do this we first need to a "First Name" and "Last Name" property in the "AspNetCoreIdentityUser" model class.

![custom add](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h181w266c1mdpw992296.png)

Once we have the entity properties set we can create our database. For this go to appsettings.json for our connection string. Here we have a default connection added by scafollded. Here we have our server "mssqllocaldb" which is a local db and database "AspNetCoreIdentity".

![connection string(https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7exjayqgmnwrlbtzip6v.png)

**Step 04:** Let's create the database. First we will add a migration then we will import the migration and update the database. This is a EF Core concept.
<center>Add-Migration InitialCreate
Update-Database</center>

After adding the migration we will see the following "Migration" folder added with the file structure.

![command](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hai16jl9x6dg1dd197br.png)

And in the "InitialCreate" file we can see the our "First Name" and "Last Name" added to the "AspNetUsers" table.

![migration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j30v1stn4585dp8ig4gl.png)
![update](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nj6l1lpjb9k91ilnbi2d.png)

**Step 05:** Now our database is ready. We will now work on our Register page and two new field "First Name" and "Last Name". First we need to change our input model and add definition for  "First Name" and "Last Name". As Register is a razor page we will go to the backend code and make the following changes.

![register update](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5wmmvfugwjgh4l147sws.png)
Now goto the HTML page and add these two fields.

![ui change](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pxi61gnz01k1e4758ko8.png)
Let's build the application goto Register page and we now see the new fields.

![field added](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pgwzuabra6bdnedahrzk.png)

**Step 06:** Before creating a new user we need to modify our backend as we need to configure our firstname and lastname. Goto "OnPostAsync" in Register.csghtml.cs page and add the following code.

![register newfield](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ynd41v4udxsu0dsvxiy4.png)

Now create a new user:

![create user](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dhwf40tym4x9v1mp2k7v.png)

Our user is successfully registered and this is temporary confirmation page. Click confirm account. Later we will disable this email confirmation option.

![regigtration complete](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/24zvbkbugk5pfiil3v2g.png)

Now goto Login page and put our user credential and click Login and we successfully login to our user.

![user login](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/84dc1d5ob92yg1m5j0a8.png)

**Step 07:** Now we will look into how to disable Email confirmation. First logout from your application and goto Program.cs. Here we will see that in AddDefaultIdentity section we will set RequireConfirmedAccount to false.

![email](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tul0bs2fdccqudkm6l9m.png)

Now build the application and goto Register page and create another new user.

![create](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gi5kp7p1bs2w34q8cbvy.png)

After registering we directly redirect to main page.

![disable](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bva55hdlnxgb4i8ue8ra.png)

And our data looks like below in our database:

![data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ujw4tq21d4tyeomtt2d.png)

**Step 08:** Now lets look into our identity features. Click on username which will take you to the manage profile page. Here you will see vairous option to manage our credentials like Profile, Email, Password, Two-factor authentication, personal data

![user manager](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ge33ngqfml1l5b2c75y.png)

####Fix Anonymous Authentication:
As we can see user can login successfully but our identity is still anonymous as we can see from the following watcher windows for user identity value from base class.

![isauth](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aklzdq3jufkc8akvhuws.png)

For this we need to create a cookie and server will look into this cookie to authenticate. Goto Login.cshtml.cs page and add the following Claim, Identity and Claims principle in "OnPosyAsync". Then use HttpContext.SignInAsync() which will serialize the claims principles into string and encrypt that string and save that as a cookie into httpcontext object.

![claim principle](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6bzoe8zmplfkr1wvwo4y.png)

Now when you try to login you will get the following exception page.

![middleware missing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uv3892dwciu4tv3bd9k4.png)

To fix this goto to Program.cs

![cookie name](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9r8vekle2ted5xh7r1gh.png)

Now run the app again and login you now can see that you are not anymore logged in as anonymous

![auth true](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mtd1acornum2lt92cmky.png)

####Concluiton:
Here we implemented user verification process. Then we injected the cookie authentication handlers so user do not logged in as anonymous. ASP.NET Core provides many tools and libraries to secure ASP.NET Core apps such as built-in identity providers and third-party identity services such as Facebook, Twitter, and LinkedIn.