Getting Started With ASP.NET Core 2.0 Identity And Role Management

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.

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.

  1. First, download and install Visual Studio 2017 from this link
  2. 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. 

  1. USE MASTER         
  2. GO    

 Check if the Database Exists. If the database exists then drop it and create a new DB.       

  1. IF EXISTS (SELECT [nameFROM sys.databases WHERE [name] = 'InventoryDB' )         
  2. DROP DATABASE InventoryDB         
  3. GO         
  4.          
  5. CREATE DATABASE InventoryDB         
  6. GO         
  7.          
  8. USE InventoryDB         
  9. GO    

After running the DB Script we can see as the Database has been created and tables have not yet been created.

ASP.NET Core Identity

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: 

ASP.NET Core Identity

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

ASP.NET Core Identity

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

ASP.NET Core Identity


ASP.NET Core Identity

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.

  1. "ConnectionStrings": {  
  2.     "DefaultConnection""Server= YOURSERVERNAME;Database=InventoryDB;user id= YOURSQLUSERID;password=YOURSQLPASSWORD;Trusted_Connection=True;MultipleActiveResultSets=true"  
  3.   },  
ASP.NET Core Identity

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.

  1. services.AddIdentity<ApplicationUser, IdentityRole>()  
  2.                 .AddEntityFrameworkStores<ApplicationDbContext>()  
  3.                 .AddDefaultTokenProviders();  
  4.   
  5.   
  6.             //Password Strength Setting  
  7.             services.Configure<IdentityOptions>(options =>  
  8.             {  
  9.                 // Password settings  
  10.                 options.Password.RequireDigit = true;  
  11.                 options.Password.RequiredLength = 8;  
  12.                 options.Password.RequireNonAlphanumeric = false;  
  13.                 options.Password.RequireUppercase = true;  
  14.                 options.Password.RequireLowercase = false;  
  15.                 options.Password.RequiredUniqueChars = 6;  
  16.   
  17.                 // Lockout settings  
  18.                 options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);  
  19.                 options.Lockout.MaxFailedAccessAttempts = 10;  
  20.                 options.Lockout.AllowedForNewUsers = true;  
  21.   
  22.                 // User settings  
  23.                 options.User.RequireUniqueEmail = true;  
  24.             });  
  25.   
  26.             //Seting the Account Login page  
  27.             services.ConfigureApplicationCookie(options =>  
  28.             {  
  29.                 // Cookie settings  
  30.                 options.Cookie.HttpOnly = true;  
  31.                 options.ExpireTimeSpan = TimeSpan.FromMinutes(30);  
  32.                 options.LoginPath = "/Account/Login"// If the LoginPath is not set here, ASP.NET Core will default to /Account/Login  
  33.                 options.LogoutPath = "/Account/Logout"// If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout  
  34.                 options.AccessDeniedPath = "/Account/AccessDenied"// If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied  
  35.                 options.SlidingExpiration = true;  
  36.             });  

Here is how we have added the ASP.NET Core Identity Services in our ConfigureService method.

ASP.NET Core Identity

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.

ASP.NET Core Identity

Click on the Register link to register our first User.

ASP.NET Core Identity

Migration

When we click on the Register button we can see the below page. Don’t panic with this page as for the first time we run it we need to do the Migration, just click on the Apply Migrations button. 

ASP.NET Core Identity

We can see the confirmation as Migration Applied and then click on the Try refreshing the page message.

ASP.NET Core Identity

Refresh the page and we can see the newly registered user has been logged in to our web site.

ASP.NET Core Identity

Refresh the Database

When we refresh our database, we can see all the Identity tables have been created.

ASP.NET Core Identity

We can check the aspNetUsers table to find the newly created user details.We can also see the ASPNetRoles and ASPNetUserRoles has no records as we have not yet created any roles or added users for the roles. In the next step we will add a new role as “Admin” and we will add the newly register user as Admin.

ASP.NET Core Identity

Step 5: Create Role and Assign User for Role

We use the below method to create a new Role as “Admin” and we will assign the recently registered as “Admin” to our website. Open  Startup.cs file and add this method in your Startup.cs file.

  1. private async Task CreateUserRoles(IServiceProvider serviceProvider)  
  2.         {  
  3.             var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();  
  4.             var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();  
  5.   
  6.   
  7.             IdentityResult roleResult;  
  8.             //Adding Addmin Role  
  9.             var roleCheck = await RoleManager.RoleExistsAsync("Admin");  
  10.             if (!roleCheck)  
  11.             {  
  12.                 //create the roles and seed them to the database  
  13.                 roleResult = await RoleManager.CreateAsync(new IdentityRole("Admin"));  
  14.             }  
  15.  //Assign Admin role to the main User here we have given our newly loregistered login id for Admin management  
  16.             ApplicationUser user = await UserManager.FindByEmailAsync("syedshanumcain@gmail.com");  
  17.             var User = new ApplicationUser();   
  18.             await UserManager.AddToRoleAsync(user, "Admin");   
  19.   
  20.         }  

From Startup.cs file we can find the Configure method. Call our CreateUserRoles method from this Configure method. When we build and run our application we can see new Role as “Admin” will be created in ASPNetRole table.

ASP.NET Core Identity

When we build and run the application we can see the New Role has been added in the ASPNetRoles table and also, we can see our default User has been assigned with the Admin Role.

ASP.NET Core Identity

Step 6: Create Admin Page and Set Authorization

Now we have an Admin user for our ASP.NET Core web application. Let's create one new page and set Authorization for this page, as only LoggedIn and Admin users can view it. For doing this we will create a new Controller named Admin.

Creating Admin Controller

Right Click Controller folder and click Add New Controller, Select MVC Controller – Empty and click Add.

ASP.NET Core Identity

Enter your Controller name as Admin and click Add.

ASP.NET Core Identity

From the controller Right Click the Index and click Add View. Click the Add Button to create our View page.

ASP.NET Core Identity

We can see our Admin Controller and Admin View has been created.

ASP.NET Core Identity

Open the Admin/Index.cshtml page to design for your need. Here I have added simple text like below.

ASP.NET Core Identity
Next, we create a new Menu to display the Admin Page. For creating our new Menu open the _Layout.cshtml from Views/Shared folder. Add the menu like the below image.

ASP.NET Core Identity

Now we have created the Admin Page and also added the menu for our Admin. We have created this page only for the Admin user and other users or non loggedin users should not see this page. 

We can see a new menu. “Admin Page,” has been created and it's open to all now. This means anyone can click on the link and view the contents of that page.

ASP.NET Core Identity

Here we can see that we can view the Admin page with our Login:

ASP.NET Core Identity

Set Authorization

To avoid this, we use the Authorization in our Admin page controller. Open our Admin Controller and add the below line of code.

  1. [Authorize(Roles = "Admin")]  
  2. public IActionResult Index()  
  3. {  
  4.     return View();  
  5. }  
ASP.NET Core Identity

If we run our application and click on the Admin page it will automatically redirect to the Log in page.

ASP.NET Core Identity

Note only the Admin Role Members are able to view the admin page as we have set the Authorization only for the Admin Roles. If you want to add more Roles we can use a comma like in the below code.

[Authorize(Roles = "Admin,SuperAdmin,Manager")]

Step 7 - Show Hide Menu by User Role

Now let’s go one step forward to show the Admin Menu only for the Loggedin Admin users. To do this we open our Layout.cshtml from Views/Shared folder and edit the newly added menu like the below code. Here in this code first we check whether the user is Authenticated, which means Loggedin, and then we check whether the user has Authorization to view the menu.

  1. <li>  
  2.                    @if (User.Identity.IsAuthenticated)  
  3.                    {  
  4.                     @if (User.IsInRole("Admin"))  
  5.                        {  
  6.              <a asp-area="" asp-controller="Admin" asp-action="Index">Admin Page</a>  
  7.                        }  
  8.                     }  
  9.                </li>  

Here is how our code will look.

ASP.NET Core Identity

Run the application and we can see by default the “Admin Page” will not be displayed in our top menu. Only Logged in Admin Role user alone can view the menu.

ASP.NET Core Identity

Let’s try this and log in with our Admin user which we created initially.

ASP.NET Core Identity

After logging in we can see the Admin user can view the Admin Page menu now.

ASP.NET Core Identity

Let’s try creating a normal user ro  register  now.

ASP.NET Core Identity

After the registration we can see that for this user we didn’t add the “Admin” role and he has no access to view the Admin Page.

ASP.NET Core Identity

Reference Link - https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?tabs=visual-studio%2Caspnetcore2x

Conclusion

Firstly, create a sample InventoryDB Database in your SQL Server. In the appsettings.json file, change the DefaultConnection connection string with your SQL Server Connections. In Startup.cs file add all the code as we discussed in this article. In the next article, we will see in detail how to perform User Role Management and customize the User Registration/Login Page in ASP.NET Core 2.0.