How to Setup and Configure Identity Membership System in ASP.NET Core

How to Setup and Configure Identity Membership System in ASP.NET Core

ASP.NET Core Identity is a membership system with which you can add login functionality to your ASP.NET application. Users can create an account and login with a user name and password. ASP.NET Core Identity uses a SQL Server database to store user names, passwords, 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 2016 LocalDB option from the Individual Components section.

Create the Example Project

For understanding the 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 2.0.

Installing Entity Framework Core

ASP.NET Core Identity system needs Entity Framework Core (EF Core) installed in the Project. EF Core is an Object/Relational Mapping (O/RM) framework, an enhanced version of ADO.NET, which automates data storage and retrieval from the database.

To Install EF Core in your project install the following 3 things given below:

1. Install EF Core DB Providers

Go to Tools > NuGet Package Manager > Package Manager Console and execute the command PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer.

install ef core db providers

2. Install EF Core Tools

Go to Tools > NuGet Package Manager >Manager NuGet Packages for Solution, and search for Microsoft.EntityFrameworkCore.Tools. Once you get the result, install the first one.

install ef core tools

3. Install EF Core Command Line Tools

Installation of dotnet CLI is done in a different manner. Right click on the Project Name in the solution explorer and select Edit ‘Identity.csproj’.

The project file will open on the Visual Studio. You have to add the below lines to it and save.

<ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.2" />
</ItemGroup>

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 class and set up the MVC framework and configure middleware that will be needed for the project. The updated code of the Startup.cs class is given below:

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

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

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseStatusCodePages();
            app.UseDeveloperExceptionPage();
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
        }
    }
}

Creating Views

Create ‘Views’ folder in the root of your project, and inside it create ‘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 ‘MVC View Layout Page’ 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>
    <title>Users</title>
    <meta name="viewport" content="width=device-width" />
    <link href="/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
</head>
<body class="m-1 p-1">
    @RenderBody()
</body>
</html>

Bower and Bootstrap

Right click on the root folder of your project, and select ‘Add > New Item’. From the item list, select ‘Bower Configuration File’ and click the ‘Add’ button. This will add ‘bower.json’ file.

Next add the bootstrap package inside the dependencies node and save it. On saving, the bootstrap package will be added to your project inside the ‘wwwroot > lib’ folder.

{
  "name": "asp.net",
  "private": true,
  "dependencies": {
    "bootstrap": "v4.1.3"
  }
}

ViewImports and ViewStart

Right click on the ‘Views’ folder and select ‘Add > New Item’. On the items list, select ‘MVC View Imports Page’ 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 ‘MVC View Start Page’ and click the ‘Add’ button.

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

@{
    Layout = "_Layout";
}

It 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, and 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, this class does not contain any property or method. This is because the IdentityUser class provides it with some of the properties like – the user’s 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.

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, 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. I have defined the User class as ‘AppUser’ in the above section.

The DB Context Class is derived from the IdentityDbContext where T is the User class (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 ‘AppIdentityDbContext’, and 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 sufficient to operate on the User class.

Database Connection String

In EF Core the 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.

So, right click the project name in the Solution Explorer, and select ‘Add > New Item’. Then on the list of items, select ASP.NET Configuration File, and click the ‘Add’ button.

The appsettings.json will be created and opened for editing in the Visual Studio. It will have the initial code as shown below:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;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.

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.

Change the database name to ‘IdentityDB’ in your connection string:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database= IdentityDB;Trusted_Connection=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 updated Startup.cs class code is:

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

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.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseStatusCodePages();
            app.UseDeveloperExceptionPage();
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
        }
    }
}

First you have to add a constructor to receive an object of type ‘IConfiguration’. It will be provided by the Depenedency Injection feature. The added code is:

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

Next, inside the ConfigureServices method I instruct the project from where it has to get the connection string to the database.

I used AddDbContext method to apply the DB Context Class (that I created earlier) and specify 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

I have to now do the ASP.NET Core Identity Configuration on the setup class. The updated code for Startup.cs class is given below:

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

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.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseStatusCodePages();
            app.UseDeveloperExceptionPage();
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
        }
    }
}

First, 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 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 of the Startup class. It is shown below:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseStatusCodePages();
    app.UseDeveloperExceptionPage();
    app.UseStaticFiles();
    app.UseAuthentication();
    app.UseMvcWithDefaultRoute();
}

It means on every HTTP Request, the user’s credentials will be added on a Cookie or URL rewriting. This will associate a give user with the HTTP request he makes.

So now the Startup.cs file is ready with its full configuration, and it will look like:

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

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.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseStatusCodePages();
            app.UseDeveloperExceptionPage();
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseMvcWithDefaultRoute();
        }
    }
}

Creating the Identity Database using the EF Core Migration Commands

Now I am ready to create my Identity Database. I will use Entity Framework Migration commands to do it for me.

To run these Migration Commands I will use the Package Manager Console window.

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

First I need to go the directory of my 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 run 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 IdentityDB database which is created:

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.

You can now learn to Create, Read, Update & Delete users in Identity Membership System in ASP.NET Core.

Share this article -

yogihosting

ABOUT THE AUTHOR

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