A Step-by-Step Guide to Implementing Identity in ASP.NET Core MVC

A Step-by-Step Guide to Implementing Identity in ASP.NET Core MVC

Are you ready to enhance your ASP.NET Core MVC project with the power of Identity? In this comprehensive guide, we'll walk you through the process of setting up and customizing the Identity system in your web application. By the end of this tutorial, you'll be able to implement secure user authentication and authorization for your ASP.NET Core project.

Step 1: Create a New ASP.NET Core Web App

Begin by opening Visual Studio and selecting "ASP.NET Core Web App (Model-View-Controller)" as your project template. Follow these steps:

1. Open Visual Studio and create a new project, selecting "ASP.NET Core Web App (Model-View-Controller)".

2. In the "Configure your project" window, enter the project name and choose the project's location.

3. In the "Additional Information" window, select the framework and choose "Individual Accounts" as the Authentication type.

Individual Accounts
4. Click "Create" to generate your project.

Step 2: Configure Your Database Connection

To set up Identity, you'll need a database. Follow these steps to configure your connection:

1. In the project, locate and open the "appsettings.json" file.

2. Modify the "DefaultConnection" string to point to your SQL database.

{
"ConnectionStrings": {
"DefaultConnection": "Server=DESKTOP-C64RV74\\SQLEXPRESS;Database=SampleDB;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=True;TrustServerCertificate=True;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
  

Step 3: Update the Database

Use the Package Manager Console to apply the database changes:

1. Open the Package Manager Console.

2. Run the command `update-database` to update the database with the Identity schema.

update-database

Step 4: Register Identity Services

1. In your "program.cs" file, add the following code to register Razor Pages as a service:

builder.Services.AddRazorPages();

2. Configure Identity options to customize its behavior by adding this code:

builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();

builder.Services.Configure<IdentityOptions>(options =>
{
    // Password Setting
    options.Password.RequireDigit = true;
    options.Password.RequireLowercase = true;
    options.Password.RequireNonAlphanumeric = true;
    options.Password.RequireUppercase = true;
    options.Password.RequiredLength = 6;

    // Lockout Settings
    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
    options.Lockout.MaxFailedAccessAttempts = 5;
});

Step 5: Customize Authentication Cookie

Control the behavior of the application's authentication cookie:

1. Add the following code to your "program.cs" to customize cookie settings:

builder.Services.ConfigureApplicationCookie(Options =>
{ 
    Options.Cookie.HttpOnly=true;
    Options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
    Options.LoginPath = "/Identity/Account/Login";
}); 

Step 6: Enable Authentication

Ensure that you add the following line after `app.UseRouting()` and before `app.UseAuthorization()` in your " program.cs " to enable authentication:

app.UseAuthentication();

Step 7: Scaffold Identity Pages

To add Identity pages to your project, follow these steps:

1. Right-click on your project and select "Add," then choose "New Scaffolded Item."

2. Select "Identity" in the "Add New Scaffolded Item" dialog and click "Add."

3. Choose the required Identity pages (e.g., Register, Register confirmation, login, and logout) and DbContext class and click "Add."

Scaffold Identity

Step 8: Managing Identity Pages

Now that you've added the scaffolded Razor pages to your project, you'll find them in the solution explorer under "Areas -> Identity -> Pages -> Account." These pages are essential for user registration, login, and log-out procedures. Let's dive into how they work:

Register Page:

In the register page, when a user clicks on the "Register" button, it triggers the RegisterModel.OnPostAsync action. This action is responsible for creating the user and utilizes the CreateAsync(TUser) method.


public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
...
...
...
  var userId = await _userManager.GetUserIdAsync(user);
...
...
...
}

Disable Default Account Verification:

By default, the user is redirected to the "Account.RegisterConfirmation" page, where they can confirm their account via a link. However, for a production application, it's advisable to disable automatic account verification. To require a confirmed account and prevent immediate login upon registration, follow these steps:

1. Navigate to /Areas/Identity/Pages/Account/RegisterConfirmation.cshtml.cs.

2. Set DisplayConfirmAccountLink = false in this file.

This configuration ensures that users must confirm their accounts before gaining access, enhancing security for your application.

public async Task<IActionResult> OnGetAsync(string email, string returnUrl = null)
{
   ...
   ...
   ...
   // Once you add a real email sender, you should remove this code that lets you confirm the account
   DisplayConfirmAccountLink = true;
   ...
   ...
   ...
}

Login Page:

The login page appears when a user clicks the login link or attempts to access a restricted page. When the login form is submitted, the OnPostAsync action is invoked, and it calls the PasswordSignInAsync method on the _signInManager object. This method verifies the user's credentials and grants access if they are valid.

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
  ...
  ...
  ...
  var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
  ...
  ...
  ...
}

Log Out:

When a user clicks on the "Logout" link, it invokes the LogoutModel.OnPost action. Inside this action, SignOutAsync is called, which clears the user's claims stored in a cookie, effectively logging the user out of the system.

public async Task<IActionResult> OnPost(string returnUrl = null)
{
 await _signInManager.SignOutAsync();
 ...
 ...
 ...
}

These essential Identity pages and their associated actions help create a seamless user experience while maintaining the security and integrity of your ASP.NET Core MVC application.

Step 9: Test Your Application

With Identity in place, you can now test your ASP.NET Core identity implementation:

1. Run your application.

2. Open the welcome page, click the register link, and create a new account.

Register

3. Follow the registration confirmation process.

4. Click the login link and log in using your newly created user account.

Login

Step 10: Implement Authorization

To test the authorization feature, add the [Authorize] attribute to your Index method. When you run the app, it will redirect to the login page if not logged in. Access to the welcome page is restricted to authorized users only.

[Authorize]
public IActionResult Index()
{
  return View();
}

With this step-by-step guide, you've successfully implemented Identity in your ASP.NET Core MVC application, making it more secure and user-friendly.

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

Exploring EventCallback in Blazor: Building Interactive Components