User registration and authentication are mandatory in any application when you have little concern about privacy. Hence all most all application development starts with an authentication module. In this article, we will discuss the quickest way to use ASP.NET Core Identity for User Login and Registration in a new or existing MVC application.
Sub-topics discussed :
- How to add ASP.NET Core Identity to MVC application.
- Customize ASP.NET Core Identity.
- Identity.UI Design Customization.
- Next step.
Background
ASP.NET Core Identity is an API, which provides both user interface(UI) and functions for user authentication, registration, authorization, etc. Modules/ APIs like this will really be helpful and fasten the development process. It comes with ASP.NET Core Framework and used in many applications before. Which makes the API more dependable and trustworthy.
ASP.NET Core MVC with user authentication can easily be accomplished using Identity.UI. While creating the MVC project, you just need to select Authentication as Individual User Accounts.
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. we want to customize ASP.NET Core Identity as per our requirement. That’s what we do here.
Create an ASP.NET Core MVC Project
First of all, I will create a brand new ASP.NET Core MVC application without any authentication selected. We could add ASP.NET Core Identity later into the project.
In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N). From new project window, select ASP.NET Core Web Application.
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.
Add ASP.NET Core Identity to Existing Project
To add ASP.NET Core Identity to the existing project, right-click on the project, select 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.
With this window, we are trying to override selected operations from Identity. Here I’ve selected Login and Register to demonstrate to you that how much extend we can customize the API. Default _Layout.cshtml is selected for the Identity pages. Now provide C# class names for Data context and user model using + button on right side. Finally, click on Add. Then a new Identity Area will be added into project directory with selected pages and related files.
Now update Startup.cs file as bellow.
ASP.NET Core Identity.UI uses Razor pages for user interface. Hence in ConfigureServices
, we’ve to call AddRazorPages
from services
. ASP.NET Core 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 add user authentication into the application. Now, if you navigate mentioned Identity URLs, you could see respective interface page for user login and user registration. Now let’s start each of them one by one.
Customize ASP.NET Core Identity
First of all, let’s deal with user registration for saving user credentials and profile data. The Identity API already defined a model class IdentityUser
with properties
UserName
Email
PhoneNumber
PasswordHash
– for encrypted password- etc.
Let add few more properties like first and last name to the model class. For that we can define a new model class ApplicationUser
, which inherit from API model class IdentityUser
.
There is a DbContext class AuthDbContext
[/Areas/Identity/Data/]. Instance of the class will be created through ASP.NET Core dependency injection in IdentityHostingStartup.cs [/Areas/Identity/].
The connection string AuthDbContextConnection
is saved in appSettings.json. If needed, you can change the SQL Server instance or DB as below.
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, in AspNetUsers table, you could see new columns for first name and last name.
Design Customization
First of all, 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 the same file is showing login and register links. 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[wwwroot/css/site.css] as follows.
...
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.
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 properties for first name and last name.
To save these property values to corresponding 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 first name and last name. Now if you navigate the URL /Identity/Account/Register
, you could see the following user registration form.
If you try submitting the registration form you could see that by default Identity API applies some validations to the form controls. you can override them as follows in /Areas/Identity/IdentityHostingStartup.cs.
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 in /Areas/Identity/Pages/Account/Login.cshtml. Now you can update the razor file as shown below.
Now the login form should look like this.
Finally, if you want to redirect already logged in user back to home page from login or registration page, you just need to update onGetAsync
method with following if statements in both login and register page.
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
.
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
- JWT Authentication
- Add 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 in comment box below.
Video Tutorial
We have discussed the same topic in our YouTube channel .