In this article, we discuss how to implement ASP.NET Core MVC user authentication and registration with Identity.UI.

Sub-topics discussed :

  • How to add ASP.NET Core Identity to an existing project.
  • Customize ASP.NET Core Identity .
  • Identity.UI Design Customization.
  • Next Step.

Background

ASP.NET Core MVC with user authentication can be easily accomplished using ASP.NET Core Identity UI. While creating the MVC project, you just need to select Authentication as Individual User Accounts.

Showing how to add ASP.NET Identity to an MVC Project while creating it.

The rest will be handled by ASP.NET Core Identity UI. It already contains razor view pages and backend codes for an authentication system. But that’s not what we want in most of the cases.

So in this tutorial, let’s look how to customize the ASP.NET Core Identity.

Create an ASP.NET Core MVC Project

First of all, I will create a brand new .Net Core MVC application without any authentication selected. then ASP.NET Core Identity can be added to the project with the help of the Identity Scaffolding template.

In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N). From New Project window, Select Asp.Net Core Web Application.

Image showing how to create ASP.NET Core Web API project in Visual Studio.

Once you provide the project name and location. A new window will be opened as follows, Select Web Application(Model-View-Controller), uncheck HTTPS Configuration and DO NOT select any authentication method. Above steps will create a brand new ASP.NET Core MVC project.

Showing project template selection for .NET Core MVC.

Add ASP.NET Core Identity to Existing Project

To add ASP.NET Core Identity to the existing project, right-click on the project. Add > New Scaffolded Item. from the opened window, select Identity from the left panel and click on Add. It’ll open up another window as shown below.

showing how to customize asp.net core identity

With this window, we are trying to override selected operations from Identity. Here I’ve selected Login and Register to demonstrate, to you how much extend you can customize this library. Default _Layout.cshtml is selected for the Identity pages. New class is mentioned for DbContext and User (rather than typing class name directly in text-field, use plus button on right). Finally, click on Add. then the new Identity Area will be added with selected pages and related files.

Now update Startup.cs file as bellow.

ASP.NET Core Identity.UI uses Razor pages for UI. Hence in ConfigureServices, we’ve to call AddRazorPages from services. Identity Contains following Routes,

  • /Identity/Account/Login
  • /Identity/Account/Logout
  • /Identity/Account/Register
  • etc

To add these routes into the app, Inside Configure function, while calling UseEndpoints function we’ve to call MapRazorPages function. UseAuthentication is called to enable authentication. Now, if you navigate mentioned Identity URLs, you could see corresponding interface. we’ve not yet created Database for the app, so form submission won’t work yet.

Customize ASP.NET Core Identity

First of all, I want to add the first and last name of user in user model. that we can do inside our new model class file- /Areas/Identity/Data/ApplicationUser.cs.

As mentioned in /Areas/Identity/IdentityHostingStartup.cs file, this Identity will be using connection string – AuthDbContextConnection. which is saved in appSettings.json file. If you want to change SQL Server instance or DB. you can do that. I use a difference instance and DB.

Now we can create the physical DB through DB Migration. From Solution Explorer, select the project, go to Tools>NuGet Package Manager > Package Manager Console. Then execute the following commands one by one.


Add-Migration "InitialCreate"
Update-Database

After successful DB Migration, Along with other Identity tables, inside AspNetUsers, you could see columns for First Name and Last Name.

Design Customization

First of to add visual flavors into the app, Font Awesome and Google Font-‘Roboto’ stylesheet reference are added to MVC default layout – Views/Shared/_Layout.cshml.

In this layout, you could see the partial render for _LoginPartial. it shows HTML elements for logged user with logout button. Currently inside the same file, it is showing Login and Register Link in header. we don’t have to show them in header. so update _LoginPartial as shown below.

Now let’s add following css rules in global style sheet as follows – wwwroot/css/site.css.


...
body {
    font-family: 'Roboto', sans-serif;
}

/*for tab control*/
div.login-logout-tab div.card-header {
    padding: 0px 0px 12px 0px;
}

div.login-logout-tab ul.nav-tabs {
    margin: 0px 0px -12px 0px;
}

div.login-logout-tab li.nav-item {
    width: 50%;
}

div.login-logout-tab a.nav-link {
    font-size: 25px;
    color: #495057;
    text-align:center;
}

div.card-content{
    padding : 10px 20px;
}

/*login form*/
div.login-form-icon{
    text-align:center;
}

Now we are going to show login and registration form side by side in a tab control. For that we need a nested layout page for login and register page. So let’s create _AuthLayout.cshtml in /Areas/Identity/Pages. For that right-click on Pages folder, Add>NewItem. Select Razor Layout, name the file as _AuthLayout.cshtml. Replace the file as shown below.

}

we want to show the tab control like this.

Showing application design

First of all we’ve main layout(_Layout.cshtml) and then inside that the nested layout(_AuthLayout). In place of @RenderBody(), we’ve to show html from respective razor pages based on URLs. It might be either Login Or Registration page. Inside the script section, based on current URL, we added ‘active’ class to the respective tab header.

User Registration

Now let’s look what we’ve to do in user registration form, which is inside /Areas/Identity/Pages/Account as Register.cshtml. Its a Razor Page not MVC Razor View, there are few differences. It has a view file with extension .cshtml and for handling back-end part, it has a C# file with the extension .cshtml.cs (like we had in old .aspx web form page).

The back-end contains two main functions, OnGetAsync and OnPostAsync to handle GET and POST requests respectively. Inside the registration back-end, we could see InputModel for designing the Registration Form. We’ve to update that for adding controls for first-name and last-name in user registration form.

To save these property values to correspond table – AspNetUsers. Update OnPostAsync, save the first name and last name to ApplicationUser instance before inserting into the table.

Now let’s update the razor file as follows.

I’ve set the layout to _AuthLayout.cshtml and added form controls for FirstName and LastName. Now if you navigate ‘/Identity/Account/Register’,  you could see the following user registration form.

Image showing user registration form after customization

If you test the registration form you could see, by default Identity apply some validations to the form controls. you can override them as follows in /Areas/Identity/IdentityHostingStartup.cs file.

By default, there should be at least one lowercase and uppercase character, we’ve disabled that here. The confirmation of email address before first login is also disabled.

Login Form

User authentication or login is handled inside – /Areas/Identity/Pages/Account/Login.cshtml. Now you can update the razor html as follows.

Now the login form should look like this.

Showing screenshot of login in asp.net core mvc

Now, this login form should work as we expect. Finally, if you want to redirect the user back to home from login or registration when he/ she is already logged in. you just need to add following if statement in login and register page, inside the function onGetAsync as shown below.

Finally, you could protect controllers or actions from unauthorized request using Authorize attribute. If there is any unauthorized request made, user will be redirected to login page. I’ve done the same in HomeController.

file – Controllers/HomeController.cs

Next Step

Here we have tried to override and customize ASP.NET Core Identity library for basic authentication. There are lot of things to be implemented like

  • Email Confirmation
  • Forgot Password
  • Use of JWT Authentication
  • Incorporate with External Authentication like Facebook, Google, etc.

We’ll let you know once we post articles on these topics. If you have any query related to ASP.NET Core Identity let me know.

Step By Step Video Tutorial

In our YouTube channel, we have discussed the same topic.