DEV Community

Sabah Shariq
Sabah Shariq

Posted on

ASP.NET Core Identity: Registration, Login and Logout

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

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

Uncheck Authentication

And running the project will show the following webpage:

Default Webpage

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

options

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

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

project structure

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

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

default page

Regisyer Login

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

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

exception page

login page

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

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.

Add-Migration InitialCreate
Update-Database

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

command

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

migration
update

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
Now goto the HTML page and add these two fields.

ui change
Let's build the application goto Register page and we now see the new fields.

field added

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

Now create a new user:

create user

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

regigtration complete

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

user login

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

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

create

After registering we directly redirect to main page.

disable

And our data looks like below in our database:

data

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

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

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

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

middleware missing

To fix this goto to Program.cs

cookie name

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

auth true

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.

Top comments (0)