ASP NET Core Identity Tutorial

In this tutorial, we will learn how the ASP.NET  Core Identity works in ASP.NET Core application. We will build an ASP.NET Core MVC application without Authentication and add the identity-related Components. We will build a User Registration & Login Page.

ASP NET Core Identity

ASP NET Core Identity is used for managing user credentials in the ASP.NET environment. You can read about it from the tutorial Introduction to ASP.NET Identity. It provides the necessary functionality to manage users, roles, claims etc. It also provides options for two-factor authentication, password reset, email confirmation etc.

This is a part of the step by step tutorial, which helps you to understand ASP.NET Identity User Management system from Scratch and explains each component in details

  1. Introduction to ASP.NET Identity
  2. ASP.NET Identity Tutorial – Getting Started
  3. ASP.NET Identity Tutorial – OWIN Authentication Middleware
  4. ASP.NET Core Identity

Creating a New Project

Open a New Project in Visual Studio 2017.

Choose ASP.NET Core Web Application Template and name the Project as ASPNetCoreIdentity Click OK

Choose the Platform as .NET Core and select the Version ASP.NET Core 2.0. Choose the template as Web Application (Model-View-Controller). Select Authentication as No Authentication. Click OK to create the new Project

Run the project to check if everything is alright.

ASP.NET Identity Core Dependencies

The New ASP.NET Core 2.0 comes with Microsoft.AspNetCore.All meta package. When you install this meta package from the NuGet, It pulls down all the related and commonly required ASP.NET Assemblies and installs it our solution.

Since we had chosen Web Application (Model-View-Controller), while creating the project, the above package is automatically installed for us.

The following Assemblies are installed, which are related to ASP.NET Identity system

  • Microsoft.AspNetCore.Identity
  • Microsoft.AspNetCore.Identity.EntityFrameworkCore
  • Microsoft.AspNetCore.Authentication
  • Microsoft.AspNetCore.Abstractions
  • Microsoft.AspNetCore.Cookies
  • Microsoft.AspNetCore.Facebook
  • Microsoft.AspNetCore.Google
  • Microsoft.AspNetCore.jwtBeare
  • Microsoft.AspNetCore.MicrosoftAccount
  • Microsoft.AspNetCore.oAuth
  • Microsoft.AspNetCore.OpenIDConnect
  • Microsoft.AspNetCore.Twitter

Preparing the Database

In the ASP.NET MVC Application, the connection strings are stored in web.config file. In the ASP.NET Core application, this has moved to appsettings.json file

let us use the localdb to store the identity data.

Open the appsettings.json and add the connection string as follows

Identity Models

IdentityUser

Now, time to define the identity models

IdentityUser is a concrete class defined in Microsoft.AspNetCore.Identity namespace. A Peek into the definition of the class shows us the following properties.

This class captures the important information about the user.

We can use this class directly in our application. But it is better if we define our own class and inherit from the above class. That allows us to extend the user class and add more information like address etc

Select the models folder and create the class ApplicationUser.cs

Add the following code

The Microsoft.AspNetCore.Identity also defines the following domain classes

  • IdentityRole
  • IdentityUserRole
  • IdentityUserClaim
  • IdentityUserLogin
  • IdentityUserToken
  • IdentityRoleClaim

Configure Entity Framework

Database Context

The DBContext is the class, which provides API to interact between Entity Framework entity models and the database. We create this class by deriving from the Microsoft.EntityFrameworkCore.DbContext class.

ASP.NET Identity comes with Entity Framework Core Identity package, which contains Entity framework implementation for storing the user information in the SQL Server database.

The Microsoft.AspNetCore.Identity.EntityFrameworkCore namespace implements the IdentityDbContext<TUser> which inherits from DbContext. This class provides the ready DbSets for all the identity models like Users and Roles.

Hence, we can create our ApplicationDbContext inherit from the IdentityDbContext<TUser>. Here TUser is our ApplicationUser.

Go to the project folder create a folder named Data.

In the Data folder create a class ApplicationDbContext.cs and add the following code

Note, that we are not passing the connection string to the constructor of the DbContext, like in the previous versions of the Entity Framework. Instead, it takes DbContextOptions in its constructor

In the previous version of ASP.NET MVC, we used OWIN context to get the instance of the DBContext

The ASP.NET core now comes with new dependency injection framework, where you can simply ask for the required services in the constructor of the class. To do that first we need to configure the services in the Startup class

Open the Startup class from the root folder

Locate the ConfigureServices method. This is where we are going to configure all the services for dependency injection

Import the following namespaces

Add the following code inside the ConfigureServices method

The AddDbContext is an extension method defined in the Microsoft.EntityFrameworkCore framework

We need to provide the DbContextOptions to the AddDbContext method

The options.UseSqlServer lets it use the SQL Server

The connection string is retrieved from the Configuration.GetConnectionString(“DefaultConnection”)

Configuring the Identity Services

The next step is to Configure the services related to ASP.NET Identity for the dependency injection

Open the Startup class.

Import the following namespaces

The goto the configure method and the following code

The AddIdentity method is an extension method defined in Microsoft.AspNetCore.Identity namespace. It is a helper method used to register the services related to in the dependency injection.

We need to tell Identity which classes to use for IdentityUser and IdentityRole. Our ApplicationUser class extends the IdentityUser, hence we are using it here

Next, we have AddEntityFrameworkStores extension method from the Microsoft.AspNetCore.Identity.EntityFrameworkCore , which registers Entity Framework related services

Finally, AddDefaultTokenProviders()  adds the Token Provider services that are exclusively used to generate opaque tokens for account operations (like password reset or email change) and two-factor authentication.

Adding Identity in the Pipeline

Open the Startup.cs

Go to Configure method. 

Add the following code after the line containing app.UseStaticFiles();

The above method adds authentication capability to the application. This extension method is defined in the Microsoft.AspNetCore.Authentication namespace.

The  UseAuthentication adds authentication middleware to the request pipeline. The .Net Core Versions up to 1.1  used the UseIdentity., which is now deprecated.  The UseAuthentication middleware sets up the cookie middleware. 

When the user logs in for the first time, this middleware serializes a user principal into an encrypted cookie and sends it to the Browser. On subsequent requests, it reads the cookie, validates the cookie, recreates the user principal, and assigns it to the HttpContext.User property. This you can then access in your controller Property using Request.User

Generate the database

One of the major things that changed in the Entity Framework is that it does not create the database without using migrations.

Let us generate the migrations and create the database using command line

But before that install the following packages

Install-package Microsoft.EntityFrameworkCore.Tools
Install-package Microsoft.EntityFrameworkCore.Tools.DotNet

Now, select and right click on the project and edit .csproj.

Add the following 

Now, open the console ( or open the command prompt and goto project folder)

To create the migration named “Initial”

And then create the database using

We have completed the setup needed to use ASP.NET Core Identity. Now let us build User registration and login pages.

User Registration

Let’s Start with registering the User

RegiserViewModels

Goto Models folder

Create a folder AccountViewModels

Create a class RegisterViewModel.cs and copy the following code

Account Controller

Select Controller folder and right click to add a new controller.

If you adding the controller for the first time “Add Dependencies to enable scaffolding” dialogue box appears. Select Full Dependencies and click on ok

Select MVC Controller- Empty. Enter the Name as AccountController. Click on Add to Add the Controller

Import the following namespaces

User Manager 

The UserManager<TUser> is a concrete class that manages the user. It is defined in the Microsoft.Extensions.Identity.Core namespace. This Class Creates, Updates, and Deletes the Users. It has methods to find a user by User ID, User Name, and email. It also provides the functionality for adding Claims, removing claims, add and removing roles, etc. It also generates password hash, Validates Users etc.

Sign In Manager

SignInManager is a concrete class which handles the user sign in from the application.  It is defined in the Microsoft.AspNetCore.Identity namespace.

The SignInManager is responsible for Authenticating a user, i .e  signing in and signing out a user. It issues the authentication cookie to the user. 

Dependency Injection

Use the dependency injection to get the UserManager and SignInManager in the constructor of the AccountController

Helper methods 

Register Action methods

Let us look at each line of code

First, We are creating a new applicationUser instance for the user input.

var user = new ApplicationUser { UserName = model.Email, Email = model.Email };

Next, we are using CreateAsync Method of the UserManager to create the user in the database.

var result = await _userManager.CreateAsync(user, model.Password);

The above method returns result which is of type IdentityResult. It has two properties. One is Succeeded which is boolean value and the other is errors property, which is a collection of errors

If the user is registered successfully, we are then calling the method SignInAsync to sign in the user. 

await _signInManager.SignInAsync(user, isPersistent: false);

View Imports

The _ViewImports.cshtml is where we put our common using statements. These are then automatically injected into the views.

Go to the View Folder and open _ViewImports.cshtml

Register View

Select Register method of the Account Controller, right-click to Add View

Keep the Template Empty, Tick Use a layout page option

Goto Account folder under Views folder and Open Register.cshtml

Copy the following code

Layout Page

Goto the shared folder under the Views folder.  Open the _Layout.cshtml

Now, locate the <li><a asp-area=”” asp-controller=”Home” asp-action=”Contact”>Contact</a></li> and insert the@await Html.PartialAsync(“_LoginPartial”)after the  </ul> tag

Partial Login View

Goto the Shared folder under Views folder and create a Partial View _LoginPartial.cshtml

Register the User

Now, you can run the code and click on Register menu to create a new user.

Login Screen

Next, let us build the Login Page

Login View Model

Goto Models -> AccountViewModels folder

Create LoginViewModel.cs and add the following code.

Login Action method

Open the AccountController.cs and add the following Code

Import the namespace

Then, copy the login action method

We are invoking PasswordSignInAsyncto verify and issue an authentication cookie

var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);

The PasswordSignInAsync method uses the UserManager to validate users email and password. It then issues the encrypted authentication cookie, which contains user’s claims.

The lockoutOnFailure, if set to true then locks out the user after 5 failed login attempts. You can override this in configuration.

The SignInManager returns SignInResult, which has four properties SucceededIsLockedOutIsNotAllowed, and
RequiresTwoFactor

Lockout action

Add this to Account Controller. 

Login View

Select Login Action method of the Account Controller, right-click to Add View

Keep the Template Empty, Tick Use a layout page option

Goto Account folder under Views folder and Open Login.cshtml

Copy the following code

The new inject keyword allows us to inject services into razor views. We use that to inject SignInManager

@inject SignInManager<ApplicationUser> SignInManager

The SignInManager is used the check and display external logging options in the view. The code SignInManager.GetExternalAuthenticationSchemesAsync()).ToList() gets the list of available External login providers. You can then loop through them @foreach (var provider in loginProviders) to display login buttons to each of them

Logout action method

Finally, add the log out Action method to the Account Controller

The SignOutAsync() method Signs out the current user and delete their cookie.

That’s it

Now, run the application and check the registration and login functionality.

Conclusion

We learned how to ASP.NET Identity in ASP.NET Core by building an application from  Scratch.

14 thoughts on “ASP NET Core Identity Tutorial”

  1. It was very helpful article. Thanks. Btw tip for the future adepts. If you want to do system where there is no registration, only logging in. Don’t create user by yourself in DB, just add a one using _signInManager. Build an object of ApplicationUser and add it by manager. Oh boy how i spend a lot of time searching why I can’t log in. Anyhow thanks for article.

  2. Good step- by- step tutorial for Identity. When I ran my code, I found that I could login successfully but I had no access to the pages login granted me access to. In the _LoginPartial.cshtml, the linline:
    @if (SignInManager.IsSignedIn(User)) always returned false even if the login was successful. The cookie settings in Firefox prevented the @if (SignInManager.IsSignedIn(User)) from returning true. It took several tries to get the cookie settings in Firefox set to allow this code to work.

    Also, it was not clear just which .cs file to put the helper methods.

    This is the best identity tutorial that I have found.

    Many thanks!

  3. when i paste this command (Install-package Microsoft.EntityFrameworkCore.Tools.DotNet)
    This sentence appeared :
    Install-package : Detected package downgrade: Microsoft.NETCore.App from 2.0.7 to 2.0.0. Reference the package directly from the project to select a different version.
    ASPNetCoreIdentity -> Microsoft.EntityFrameworkCore.Tools.DotNet 2.0.3 -> Microsoft.NETCore.App (>= 2.0.7)
    ASPNetCoreIdentity -> Microsoft.NETCore.App (>= 2.0.0)
    At line:1 char:1
    + Install-package Microsoft.EntityFrameworkCore.Tools.DotNet
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand

    Install-package : Package ‘Microsoft.EntityFrameworkCore.Tools.DotNet 2.0.3’ has a package type ‘DotnetCliTool’ that is not supported by project ‘ASPNetCoreIdentity’.
    At line:1 char:1
    + Install-package Microsoft.EntityFrameworkCore.Tools.DotNet
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand

    is there something that i missed?

  4. Error: “InvalidOperationException: The model item passed into the ViewDataDictionary is of type ‘ProjectName.Models.AccountViewModels.RegisterViewModel’, but this ViewDataDictionary instance requires a model item of type ‘ProjectName.Web.Models.ApplicationUser’.”

  5. InvalidOperationException: The model item passed into the ViewDataDictionary is of type ‘ProjectName.Models.AccountViewModels.RegisterViewModel’, but this ViewDataDictionary instance requires a model item of type ‘ProjectName.Web.Models.ApplicationUser’.

  6. wael Hosny Radwan

    Excellent Seiers of articles
    note:
    in Configuring the Identity Services
    goto ConfigureServices method instead goto configure method

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top