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.
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.
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.
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. 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 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,
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.
After successful DB Migration, Along with other Identity tables, inside AspNetUsers, you could see columns for First Name and Last Name.
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.
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.
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.
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.
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.
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
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.