ASP.NET Core Identity

What is ASP.NET Core Identity?

ASP.NET Core Identity is a membership system that allows you to add login functionality to your application. It includes features like user registration, password hashing, roles, claims, and multi-factor authentication.

  • Secure: Includes out-of-the-box support for password hashing and user authentication.
  • Extensible: Can be customized to meet specific requirements.
  • Integrated: Works seamlessly with Entity Framework Core for database interactions.

Why Use ASP.NET Core Identity?

ASP.NET Core Identity simplifies user management and security in web applications, providing essential tools to manage authentication and authorization efficiently.


How to Implement ASP.NET Core Identity

Follow these steps:

1. Install the Required NuGet Packages


// Open the NuGet Package Manager Console and run:
Install-Package Microsoft.AspNetCore.Identity.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.SqlServer

                

These packages provide Identity and Entity Framework Core functionality.

2. Configure the Database Context


// Data/ApplicationDbContext.cs
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options) { }
}

                

The ApplicationDbContext class inherits from IdentityDbContext, enabling Identity features.

3. Register Identity in the Program


// Program.cs
var builder = WebApplication.CreateBuilder(args);

// Add Identity services
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.Run();

                

Identity is registered in the dependency injection container and configured to use the database.

4. Add Default UI and Migrations


// Add Identity's default UI:
dotnet add package Microsoft.AspNetCore.Identity.UI

// Create the migration:
dotnet ef migrations add InitialIdentity

// Apply the migration:
dotnet ef database update

                

This sets up the database schema required for Identity.

5. Use Identity Features


// Add default Razor Pages for Identity
app.MapRazorPages();

                

ASP.NET Core Identity provides pre-built Razor Pages for login, registration, and account management. Visit /Identity/Account/Login or /Identity/Account/Register to use these pages.

6. Protect Routes


// Pages/Admin.cshtml
@page
@attribute [Authorize(Roles = "Admin")]

Admin Panel

Use the [Authorize] attribute to secure routes based on roles.

7. Add Roles and Seed Data (Optional)


// Seed roles and users
public static async Task SeedData(IServiceProvider serviceProvider)
{
    var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    var userManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();

    if (!await roleManager.RoleExistsAsync("Admin"))
    {
        await roleManager.CreateAsync(new IdentityRole("Admin"));
    }

    var user = new IdentityUser { UserName = "admin@example.com", Email = "admin@example.com" };
    var result = await userManager.CreateAsync(user, "Admin@123");

    if (result.Succeeded)
    {
        await userManager.AddToRoleAsync(user, "Admin");
    }
}

                

Call SeedData during application startup to seed roles and users.