How to Setup and Configure ASP.NET Core Identity

How to Setup and Configure ASP.NET Core Identity

ASP.NET Core Identity is a Toolkit and an API with which you can create Authorization and Authentication features in your application. Users can create an account and login with a user name and password. This also includes Roles and Roles Management. ASP.NET Core Identity uses a SQL Server Database to store user names, passwords, roles, and profile data.

This tutorial requires the SQL Server LocalDB feature to be installed for Visual Studio. You can add this feature by running the Visual Studio installer and installing the SQL Server Express LocalDB option from the Individual Components section.

You can also directly download this from the Microsoft website – Link

Create the Example Project

For understanding the ASP.NET Core Identity you will need to create a new ASP.NET Core MVC project called Identity. Use Core Web Application (.NET Core) template to create a new Empty Project and remember to select the framework as .NET Core and version as ASP.NET Core 3.1.

Installing Identity Packages

ASP.NET Core Identity needs 4 packages to be installed in your application. These packages are:

  • 1. Microsoft.AspNetCore.Identity
  • 2. Microsoft.AspNetCore.Identity.EntityFrameworkCore
  • 3. Microsoft.EntityFrameworkCore.Design
  • 4. Microsoft.EntityFrameworkCore.SqlServer

Install them from NuGet, first go to Tools ➤ NuGet Package Manager ➤ Manage NuGet Packages for Solutions in your Visual Studio. Then search for these packages and click install. I have provided with a screenshot of these packages in the below image.

ASP.NET Core Identity Packages
Entity Framework Core – Identity uses EF core, learn EF Core’s Installation, DBContent file, Database-First approach, migrations, Fluent API, and everything else in this series of tutorial..

Configuring the Project

Go to the Startup.cs class and set up the MVC framework and configure Middleware that will be needed for the project. The updated codes of the Startup.cs class are highlighted and given below:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Identity
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Installing Bootstrap

I will need Bootstrap package for styling the Views. So first create a new folder called wwwroot on the root of the project and then right click on it and select Add ➤ Client-Side Library. You will get a new window called Add Client-Side Library, here search for twitter-bootstrap on the library text box and click the Install button.

The Bootstrap package will be installed in a few moments. You can also read my separate tutorial on this topic – How to Install Bootstrap Package in ASP.NET Core Application in Visual Studio.

Creating Views

Create Views folder on the root of your project, and inside it create another folder called Shared folder.

Layout

Right click on the Shared folder, and select Add ➤ New Item. You will get a new window showing the item list, from this list select Razor Layout and click the Add button.

This will add _Layout.cshtml file in the Shared folder and it will be open for editing. Next, add the following code to it:

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    <link href="~/twitter-bootstrap/css/bootstrap.css" rel="stylesheet" />
</head>
<body class="m-1 p-1">
    @RenderBody()
</body>
</html>
ViewImports and ViewStart

Right click on the Views folder and select Add ➤ New Item. On the items list, select Razor View Imports and click the Add button. This will add _ViewImports.cshtml file.

Import the built-in tag helpers & models namespace for the Views, by adding the following code to this file:

@using Identity.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

In the same way, right click the Views folder and select Add ➤ New Item. On the items list, select Razor View Start and click the Add button.

This will add the _ViewStart.cshtml file with the following initial code:

@{
    Layout = "_Layout";
}

The View Start tells that all the Views will have the Layout from the _Layout.cshtml file which is located inside the Shared folder.

Setting up ASP.NET Core Identity

The process for setting up ASP.NET Core Identity involves creating new model classes, configuration changes, controllers and actions to support authentication and authorization operations.

User Class

User class defines the Users for the application. These users are stored in the database. The User class is derived from IdentityUser class of Microsoft.AspNetCore.Identity namespace.

So, create Models folder in the root of the project, and add to it a class called AppUser.cs with the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
 
namespace Identity.Models
{
    public class AppUser: IdentityUser
    {
    }
}

Notice, the AppUser.cs does not contain any property or method. This is because the IdentityUser.cs class provides it with some of the properties like the user name, e-mail, phone number, password hash, role memberships and so on.

If you want more properties that are not defined in the IdentityUser class then you can certainly add them to your User Class. I will take this in the later on sections.

The IdentityUser class properties are defined below:

Name Description
Id It contains the Unique Id of the user.
UserName It contains the user’s username.
Claims This property returns all the clams for the user.
Email It contains the email for the user.
PasswordHash It contains the hash form of the user password.
Roles It returns all the roles for the user.
PhoneNumber It returns the phone number for the user.
SecurityStamp It contains a value that is changed whenever the user identity is altered. For example a password or phone number change, etc.

DB Context Class

DB Context Class also called as Database Context Class operates on the User class. Remember I have defined the User class as AppUser.cs in the above section.

The DB Context Class is derived from the IdentityDbContext where T is the User class that is AppUser in the project.

Now, create the DB Context Class inside the Models folder. You can do it by adding a new class and give it a name as AppIdentityDbContext.cs. Next add the following code to it:

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
 
namespace Identity.Models
{
    public class AppIdentityDbContext : IdentityDbContext<AppUser>
    {
        public AppIdentityDbContext(DbContextOptions<AppIdentityDbContext> options): base(options) { }
    }
}

Notice, I haven’t added any property or method to this class, this is because this empty class is inheriting from IdentityDbContext<AppUser> and so it is getting all it’s methods and properties.

Database Connection String

The Database Connection string, which contains the Database name, user name and password to connect to the Database is mostly stored in the appsettings.json file. This file should be created in the root folder of the project.

Mostly this file is already created in a new project. If it is missing then you right click the project name in the Solution Explorer, and select Add ➤ New Item. Then on the list of items, select App Settings File, and click the Add button.

Add the following code to your appsettings.json file.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database= IdentityDB;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

In the Connection string the Server name specifies the SQL Server LocalDB, Database name specifies the name of the database which I have kept as IdentityDB. You can name it anything which you want.

The Trusted_Connection is set to ‘True’ so the project will use windows authentication to connect to this database and there is no need for providing the database username and password.

Multiple Active Result Sets (MARS) is a feature that works with SQL Server to allow the execution of multiple batches on a single connection. This gives faster execution of SQL Operations. I have set it to true – MultipleActiveResultSets=true

Now, I have to update the Startup.cs file so that the application can read the connection string from the appsettings.json file.

The changes that are made to the Startup.cs class are highlighted (see below).

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Identity.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;

namespace Identity
{
    public class Startup
    {
        public Startup(IConfiguration configuration) => Configuration = configuration;
        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppIdentityDbContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
            services.AddControllersWithViews();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //...
        }
    }
}

First you have to add a constructor to receive an object of type IConfiguration. It will be provided by the Dependency Injection feature of ASP.NET Core. The added code is:

public Startup(IConfiguration configuration) => Configuration = configuration;
public IConfiguration Configuration { get; }

Next, inside the ConfigureServices() method I instruct the project how it has to get the connection string to the database.

I used the AddDbContext() method to apply the DB Context Class (that I created earlier) and specified that it will be using the SQL Server database whose connection string is obtained from the application’s configuration file, which in my case is appsettings.json file.

The applicable code is given below:

services.AddDbContext<AppIdentityDbContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));

Set up ASP.NET Core Identity as a Service

Now I have to do the configuration of ASP.NET Core Identity on the Startup class. The updated code for Startup.cs class is given below:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Identity.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;

namespace Identity
{
    public class Startup
    {
        public Startup(IConfiguration configuration) => Configuration = configuration;
        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppIdentityDbContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
            services.AddIdentity<AppUser, IdentityRole>().AddEntityFrameworkStores<AppIdentityDbContext>().AddDefaultTokenProviders();
            services.AddControllersWithViews();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //...
        }
    }
}

Note – inside the ConfigureServices() method I have added the given code line to set up the ASP.NET Core Identity as a Service:

services.AddIdentity<AppUser, IdentityRole>().AddEntityFrameworkStores<AppIdentityDbContext>().AddDefaultTokenProviders();

The above code specifies that:

  • The AddIdentity method’s type parameter are specified with the class used to represent users (AppUser) and the class used to represent roles (Identity Role).
  • The AddEntityFrameworkStores method specifies that Identity should use EF Core and the DB Content class which in the project is AppIdentityContext class.
  • The AddDefaultTokenProviders method adds the default token providers used to generate tokens for reset passwords, change email and change telephone number operations, and for two factor authentication token generation.

The final change to the Startup class is done by adding the app.UseAuthentication() to the Configure() method. It means on every HTTP Request, the user’s credentials will be added on a Cookie or URL. This will associate a give user with the HTTP request he or she makes to the application. It is shown below:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days.
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

So now the Startup.cs file is ready with it’s full configuration. It’s complete code is given below:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Identity.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;

namespace Identity
{
    public class Startup
    {
        public Startup(IConfiguration configuration) => Configuration = configuration;
        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppIdentityDbContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
            services.AddIdentity<AppUser, IdentityRole>().AddEntityFrameworkStores<AppIdentityDbContext>().AddDefaultTokenProviders();
            services.AddControllersWithViews();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Creating the Identity Database using the EF Core Migration Commands

Now I am ready to create my Identity Database. I will use Entity Framework Core Migration commands to perform this task.

To run these Migration Commands I will use the Package Manager Console window. You will also need to install dotnet ef tool for running and managing migrations. Install dotnet ef by running the following command on the Package Manager Console window:

dotnet tool install --global dotnet-ef
If you want to learn about the migration process in EF core then kindly look into my tutorial on Migrations in Entity Framework Core.

Next you need to go the directory of the project’s Startup.cs file. For this, run the dir command on the Package Manager Console window. The dir command will tell the current directory location.

When I ran the dir command it showed me my current direction location. As shown in the image given below, there are – Identity directory and Identity.sln file but no Startup.cs file.

dir command

The Startup.cs file is located inside the Identity folder. So I have to go inside the Identity folder by using the cd ./Identity.

Then I again run the dir command and see the Startup.cs file, as shown in the image given below:

startup.cs file directory

So now I can run my EF Core Migration Commands.

The first command to run is:

dotnet ef migrations add MyCommand1

The first command will take few seconds time to complete. Once completed, it will create the SQL Statements, necessary to create the database, in a few files. These files are created inside the Migrations folder.

The second command to run now is:

dotnet ef database update

This command will create your database from the files created by the first command.

It will take a few seconds time to complete.

Once completed you can check your newly created database from the SQL Server Object Explorer window.

See the below image which shows this newly created IdentityDB database.

SQL Server Object Explorer
The SQL Server Object Explorer window can be opened from the View option given in the Visual Studio menu.

You can download the full codes of this tutorial from the below link:

Download

Conclusion

This completes the setup procedure of Identity in your application. You can now add users, manage users, add roles, add users to roles, do user authentication, and so many other things with Identity.

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.