Introduction
Adding security to your application is an important step. So that you allow only authenticated users to access the application. ASP.NET Core Identity is a powerful system that simplifies user authentication in ASP.NET Core applications. It provides a wide range of features, including user registration, login, password management, role-based authorization, and integration with external authentication providers.
In this article, you will learn how to add identity service to your ASP.NET 6 MVC project. Before getting started, let's see the basics.
What is ASP.NET Core MVC?
ASP.NET Core MVC is a powerful and flexible framework for building web applications using the ASP.NET Core platform. MVC separates the application into three different components: the model, the view, and the controller. The model represents the application's data and business logic. It encapsulates the data structures, logic, and algorithms necessary to manipulate and process the data. The view is responsible for presenting the user interface to the users. The view receives data from the model and renders it in a user-friendly format. The controller acts as the intermediary between the model and the view. The controller handles the flow of the application by receiving requests, processing them, and returning the appropriate response.
What is authentication and authorization?
Authentication and authorization are crucial aspects of application development. Authentication refers to the process of verifying the Identity of users, ensuring that they are who they claim to be. Authorization, on the other hand, is the process of granting or denying access to specific resources or functionalities based on the authenticated user's permissions and roles.
In today's digital landscape, where sensitive user data and confidential information are involved, it is essential to implement a secure authentication and authorization mechanism. It helps protect user accounts, restrict unauthorized access to sensitive data, and ensure that only authorized users can perform certain actions within the application. By implementing authentication and authorization effectively, developers can enhance the overall security and trustworthiness of their web applications.
What is ASP.NET Core Identity?
ASP.NET Core Identity is a membership system that provides built-in support for user authentication and authorization in ASP.NET Core applications. It simplifies the process of managing user accounts, passwords, and roles, allowing developers to focus on the core functionality of their applications.
In other words, ASP.NET provides the required functionality to add functionality like registering, signing in, signing out, managing users, passwords, profiles, authorization, roles, claims, tokens, email confirmation, and much more.
ASP.NET Core Identity offers a robust set of features, including user registration, login, password management, role-based authorization, and external authentication provider integration. It seamlessly integrates with ASP.NET Core MVC, making it easy to incorporate authentication and authorization capabilities into your web application.
With ASP.NET Core Identity, developers can leverage secure authentication mechanisms like cookies and JSON Web Tokens (JWT). It also provides a flexible and extensible architecture that allows customization and integration with existing user stores and providers. Whether you're building a small-scale application or a large enterprise-level system, ASP.NET Core Identity provides the necessary tools and APIs to implement secure and scalable authentication and authorization solutions.
Prerequisites
- Visual Studio 2022
- .NET 6 Framework
- MS SQL Server
How to Set up ASP.NET Core Identity In Our Project?
To do authentication using Identity, I will create the project from scratch. Now, let's create the project.
Step 1. Creating the project
Open Visual Studio 2022. Select "Create a new project" and click "Next". Select the "ASP.NET Core Web App (Model-View-Controller)" template and click on "Next".
Name your project and solution as you wish and select the location where you want to store your project, and click on "Next". We have named our project "CRMApp".
Choose the "NET 6" framework and click on the "Create" button.
Now, you have successfully created the project.
Step 2. Setting up the database
Open SSMS (SQL Server Management Server) and create and use a database.
create database SalesCRM;
use SalesCRM;
Step 3. Open appsetting.js and set the connection string.
"ConnectionStrings":
{
"SalesCRMcnn": "Server=***;Database=SalesCRM;User Id=**;Password=****;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
}
Step 4. Creating Models
Click on Models and add a new class named SalesleadEntity.cs. In this class, add the required properties for the model as shown below.
namespace CRMApp.Models
{
public class SalesLeadEntity
{
public int Id { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public string? Mobile { get; set; }
public string? Email { get; set; }
public string? Source { get; set; }
}
}
Step 5. Adding Required Packages
Now, Right click on the project and select "Manage NuGet Packages". In the browse section, search the following packages and install them.
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
- Microsoft.AspNetCore.Identity.EntityFrameworkCore
Now, Create a new folder named "Data" in the project and add a new class named "ApplicationDbContext.cs".
using CRMApp.Models;
using Microsoft.EntityFrameworkCore;
namespace CRMApp.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<SalesLeadEntity> SalesLead { get; set; }
}
}
Now, open program.cs, and add the following service in the file.
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("SalesCRMcnn")));
Step 6. Adding the migration to the database
To add migration to the database, Go to "Tools" -> "NuGet Package Manager" -> "Package Manager Console", and the package manager console will open.
In the console, run the following commands.
add-migration "Initial migration"
Update-database
After running the above commands, a migration file will be added to your project, having folder name Migrations, and the database will be updated.
Step 7. Adding Controller
Click on Controller and add a new Scaffolded Item and select "MVC Controller with views, using Entity Framework," and click on "Add". A popup will open like this.
Choose "SalesLeadEntity" as the model class and "ApplicationDbContext" as DbContext class. Also, name the controller "LeadsController". Click on "Add", and a new controller will get created with action methods in it.
Now, go to "_Layout.cshtml" and add the following lines to make a new menu for the Sales Lead.
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Leads" asp-action="Index">Sales Lead</a>
</li>
Now, if you will run the project and open the index page, you will have an empty page like this.
Here, click "Create New" to create a new record.
Once you add the records on the index page, you will have that records.
Step 8. Securing the project using Identity
Before adding Identity to the project, update the "ApplicationDbContext.cs" with the below code, as now we will be inheriting IdentityDbContext instead of DbContext.
using CRMApp.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace CRMApp.Data
{
public class ApplicationDbContext : IdentityDbContext
{
...
}
}
Now, Right Click on the project and click on "Add new Scaffolded Item". Click on "Identity" and then click "Add".
Here, I have selected all options, but you can select according to your need and project requirements. Choose DbContextClass as "ApplicationDbContext" and Click on "Add".
Now, you will have Identity added to your project using scaffolding. Now, you will see a folder named Areas which has a sub-folder named Identity which contains a sub-folder names Account which has endpoints for login register, logout, etc in the form of razor pages.
Step 9. Adding necessary code and updating the database
Open "_Layout.cs", and add the following code in the <nav> section before the </nav>
<partial name="_LoginPartial"/>
Now, you should be able to see Login and Register options in the right-side menu when running the project.
Add the following line in the Program.cs.
app.MapRazorPages();
Now, you will have to add migration to the database; go to "Tools", click on "NuGet Package Manager" and then on "Package Manager Console", the package manager console will open.
In the console, run the following commands.
add-migration "Identity tables migration"
Update-database
Here, a new migration file will be added to the Migration folder, and necessary tables are added to the database.
Step 10. Create a new account
Run the project and click on register to register users. A Register page will open like the one below.
Here, you can register users by filling in the fields given.
But, if you click on Sales Lead, you will see you can still access the sales lead page without logging. So, to prevent this, follow the next step.
Step 11. Adding security
Go to "LeadsController.cs" and add attribute [Authorize] at the controller level.
namespace CRMApp.Controllers
{
[Authorize]
public class LeadsController : Controller
{
...
}
}
Now, if you will open the application and click on Sales Lead, you will see that you cannot access the page without logging in yourself. A page for login will open for you, as shown below.
Once you log in yourself using the email and password. You will be able to access the Index page with Sales Lead Details. Also, you will have options to edit, get details and delete the records.
Here, you can see the details.
As you have seen, we have successfully added authentication to our ASP. NET 6 projects using the Identity Service.
Conclusion
ASP.NET Core Identity is a powerful tool for implementing user authentication and authorization in ASP.NET Core applications. By leveraging its features, developers can easily incorporate secure and scalable authentication mechanisms into their web applications, enhancing overall security and user trust. ASP.NET Core Identity simplifies the process of managing user accounts, passwords, and roles, allowing developers to focus on the core functionality of their applications. With its seamless integration with ASP.NET Core MVC, developers can create robust user management functionality and ensure that only authorized users can access specific resources or functionalities within the application.
By following the steps outlined in this article, developers can successfully set up ASP.NET Core Identity in their projects and enjoy the benefits of a secure and efficient authentication system.