Introduction
In this article, we will see in detail how to use ASP.NET Core Identity in MVC Application for creating user roles and displaying the menu depending on user roles.
Here, we will see how to,
- Create default admin users.
- Create default admin role.
- Redirect unauthenticated users to a login page.
- Display Admin Page menu only for Authorized Admin User.
ASP.NET Identity allows us to add login functionality to our system. Here, in this demo, we will be using SQL Server to store the user details and profile data. We will use ASP.NET Identity for new user registration, login, and to maintain the user profile data. If we talk about the login, the important part is whether the logged in user is authenticated and also authorized to view the pages.
Authentication and Authorization
Authentication
Check for the Valid User. Here, the question is how to check whether a user is valid or not. When a user comes to a website for the first time, he/she will register for that website. All their information, like username, password, email, and so on will be stored in the website database. When a user enters his/her userID and password, the information will be checked with the database. If the user has entered the same userID and Password as in the database, then he or she is a valid user and will be redirected to the website's home page. If the user entered UserID or Password that does not match the database, then the login page will give a message, something like “Enter valid Username or Password”. The entire process of checking whether the user is valid or not for accessing the website is called Authentication.
Authorization
Once the user is authenticated, they need to be redirected to the appropriate page by his/her role. For example, when an Admin is logged in, then need to be redirected to the Admin Page. If an Accountant is logged in, then he/she needs to be redirected to his Accounts page.
Prerequisites
Make sure you have installed all the prerequisites in your computer. If not, then download and install them all, one by one.
- First, download and install Visual Studio 2017 from this link
- SQL Server 2014 or above
Using the code
Step 1: Create a Database
Firstly, we will create a Database and set the connection string in appsettings.json file for DefaultConnection with our new database connection. We will be using this database for ASP.NET Core Identity table creation.
Create Database: Run the following script to create our database.
- USE MASTER
- GO
Check if the Database Exists. If the database exists then drop it and create a new DB.
- IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'InventoryDB' )
- DROP DATABASE InventoryDB
- GO
- CREATE DATABASE InventoryDB
- GO
- USE InventoryDB
- GO
After running the DB Script we can see as the Database has been created and tables have not yet been created.

Step 2: Create your ASP.NET Core
After installing our Visual Studio 2017, click Start, then Programs and select Visual Studio 2017 - Click Visual Studio 2017. Click New, then Project, select Web and then select ASP.NET Core Web Application. Enter your project name and click:

Select Web Application (Model-View-Controller) and click on Change Authentication

Select Individual User Accounts and click ok to create your project.


Updating appsettings.json
In appsettings.json file we can find the DefaultConnection Connection string. Here in connection string change your SQL Server Name, UID and PWD to create and store all user details in one database.
- "ConnectionStrings": {
- "DefaultConnection": "Server= YOURSERVERNAME;Database=InventoryDB;user id= YOURSQLUSERID;password=YOURSQLPASSWORD;Trusted_Connection=True;MultipleActiveResultSets=true"
- },

Step 3: Add Identity Service in Startup.cs file
By default, in your ASP.NET Core application the Identity Service will be added in Startup.cs File /ConfigureServices method. You can also additionally add the password strength and also set the default login page/logout page and also AccessDenaiedPath by using the following code.
- services.AddIdentity<ApplicationUser, IdentityRole>()
- .AddEntityFrameworkStores<ApplicationDbContext>()
- .AddDefaultTokenProviders();
- //Password Strength Setting
- services.Configure<IdentityOptions>(options =>
- {
- // Password settings
- options.Password.RequireDigit = true;
- options.Password.RequiredLength = 8;
- options.Password.RequireNonAlphanumeric = false;
- options.Password.RequireUppercase = true;
- options.Password.RequireLowercase = false;
- options.Password.RequiredUniqueChars = 6;
- // Lockout settings
- options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
- options.Lockout.MaxFailedAccessAttempts = 10;
- options.Lockout.AllowedForNewUsers = true;
- // User settings
- options.User.RequireUniqueEmail = true;
- });
- //Seting the Account Login page
- services.ConfigureApplicationCookie(options =>
- {
- // Cookie settings
- options.Cookie.HttpOnly = true;
- options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
- options.LoginPath = "/Account/Login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
- options.LogoutPath = "/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
- options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
- options.SlidingExpiration = true;
- });
Here is how we have added the ASP.NET Core Identity Services in our ConfigureService method.

Step 4: Register and Create your First User
Now our Asp.NET Core web application is ready for users to register in our website and also users can log in to our system after registration. We will be doing the Authorization by adding roles to the user in the following steps. Build and run your application to register your first default Admin user.


























pmh mrhPosted Sep 3, 2020, 10:09 PM
Can we implement authentication with our own tables ? Means, I don't want to use the built in tables like, aspnet_users, aspnet_roles, etc.
MikePosted May 5, 2020, 8:14 AM
Very nice article! Do you have any updates of this article for ASP.NET Core 3
Chittaranjan SwainPosted Sep 27, 2019, 5:35 AM
Nice article.
Shailesh NikamPosted Apr 9, 2019, 1:57 AM
Thanks a lot for putting such a nice article
John VPosted Jul 30, 2018, 12:48 PM
Thank you for this article. If I may suggest, one thing both MVC and ASP.NET core articles like this don't really go into detail on is how/why the Authorize[] attribute is able to verify what roles are assigned to the user.
Kevin APosted Jul 22, 2018, 12:54 PM
This is a great article Thanks! It doesn't work for Core 2.1 . Any suggestions for ASP.NET Core 2.1.?
黄 桂兰Posted May 4, 2018, 6:54 AM
Thank you very much. It is just what I want to know.
Hiten PandyaPosted Mar 20, 2018, 2:34 AM
Superb article sir.