Click here to Skip to main content
14,454,632 members

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

Rate this:
3.54 (10 votes)
Please Sign up or sign in to vote.
3.54 (10 votes)
19 Mar 2018CPOL
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.

Background

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. 

USE MASTER       
GO       
       
-- 1) Check for the Database Exists .If the database is exist then drop and create 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 that the Database has been created and tables have not yet been created.

Image 1

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.

Image 2

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

Image 3

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

Image 4

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"
  },

Image 5

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 while the user registers 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;
            });

            //Setting 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 looks like:

Image 6

Step 4: Register and Create your First User

Now our ASP.NET Core web application is ready for user to register in our website and also user can login to our system after registration. We will be doing the Authorization by adding role to user in next steps. Build and run your application to register your first default Admin user.

Image 7

Click on the Register link to register our first User.

Image 8

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 run we need to do the Migration, just click on the Apply Migrations button.

Image 9

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

Image 10

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

Image 11

Refresh the Database

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

Image 12

We can check the aspNetUsers table to find the newly created user details. We can also see the ASPNetRoles and ASPNetUserRoles have no records as we have not yet created any roles or added user 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.

Image 13

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.

private async Task CreateUserRoles(IServiceProvider serviceProvider)
        {
            var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();

            IdentityResult roleResult;
            //Adding Admin Role
            var roleCheck = await RoleManager.RoleExistsAsync("Admin");
            if (!roleCheck)
            {
                //create the roles and seed them to the database
                roleResult = await RoleManager.CreateAsync(new IdentityRole("Admin"));
            }
 //Assign Admin role to the main User here we have given our newly registered 
 //login id for Admin management
            ApplicationUser user = await UserManager.FindByEmailAsync("syedshanumcain@gmail.com");
            var User = new ApplicationUser(); 
            await UserManager.AddToRoleAsync(user, "Admin");
        }

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.

Image 14

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 as our default User has been assigned with the Admin Role.

Image 15

Step 6: Create Admin Page and Set Authorization

Now we have an Admin user for our ASP.NET Core web application. As a next step, let's create one new page and set Authorization for this page as only Logged in and Admin user alone can view this page. For doing this, we create a new Controller named as Admin.

Creating Admin Controller

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

Image 16

Enter your Controller name as Admin and click Add.

Image 17

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

Image 18

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

Image 19

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

Image 20

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:

Image 21

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-logged in users should not see this page. What will happen If we run our application.

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

Image 22

Here, we can see as we can view the Admin page with our Login.

Image 23

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:

[Authorize(Roles = "Admin")]
public IActionResult Index()
{
    return View();
}

Image 24

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

Image 25

Note only the Admin Role Members will be 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 the comma like the below code:

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

Step 7: Show Hide Menu by User Role

Now let’s go one step forward as to show the Admin Menu only for the Logged in 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, means Logged in, and then we check whether the user has Authorization to view the menu.

<li>
                   @if (User.Identity.IsAuthenticated)
                   {
                    @if (User.IsInRole("Admin"))
                       {
             <a asp-area="" asp-controller="Admin" asp-action="Index">Admin Page</a>
                       }
                    }
               </li>

Here is how our code will look like:

Image 26

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

Image 27

Let’s try this by Login with our Admin user which we created initially.

Image 28

After Log in, we can see that the Admin user can view the Admin Page menu now.

Image 29

Let’s try with creating a normal user as we register new user now.

Image 30

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

Image 31

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

Points of Interest

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.

History

  • 2018/03/17: ASPNETCoreUserIdentity.zip

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

syed shanu
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

 
QuestionMigrations not working Pin
Exurb4-Nov-19 5:41
MemberExurb4-Nov-19 5:41 
QuestionView to Manage Logged in User Roles. Pin
smoro99925-Apr-18 3:12
Membersmoro99925-Apr-18 3:12 
AnswerRe: View to Manage Logged in User Roles. Pin
syed shanu29-Apr-18 21:32
mvasyed shanu29-Apr-18 21:32 
GeneralMy vote of 5 Pin
Hyland Computer Systems13-Apr-18 9:06
MemberHyland Computer Systems13-Apr-18 9:06 
QuestionGreat article, but...... Pin
gaujaai20-Mar-18 5:28
Membergaujaai20-Mar-18 5:28 
AnswerRe: Great article, but...... Pin
syed shanu21-Mar-18 17:50
mvasyed shanu21-Mar-18 17:50 
QuestionHow to do Identity And Role Management with asp.net mvc5 Pin
Mou_kol20-Mar-18 0:16
MemberMou_kol20-Mar-18 0:16 
AnswerRe: How to do Identity And Role Management with asp.net mvc5 Pin
syed shanu21-Mar-18 17:49
mvasyed shanu21-Mar-18 17:49 
GeneralRe: How to do Identity And Role Management with asp.net mvc5 Pin
Mou_kol21-Mar-18 23:43
MemberMou_kol21-Mar-18 23:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Article
Posted 16 Mar 2018

Stats

22.7K views
688 downloads
30 bookmarked