Section 2 of 6

ASP.NET Core Identity

🎯 What You'll Learn

  • What is ASP.NET Core Identity
  • Setting up Identity
  • User registration and login
  • UserManager and SignInManager
  • Roles and claims

What is ASP.NET Core Identity?

ASP.NET Core Identity is a membership system that adds login functionality, user management, password hashing, roles, claims, and more.

Setting Up Identity

1. Install Package

Install NuGet Package Bash
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore

2. Create User Model

Models/ApplicationUser.cs C#
public class ApplicationUser : IdentityUser
{
    public string? FullName { get; set; }
}

3. Update DbContext

Data/ApplicationDbContext.cs C#
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options) { }
}

4. Configure Services

Program.cs C#
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

5. Run Migrations

Create and Apply Migration Bash
dotnet ef migrations add AddIdentity
dotnet ef database update

User Registration

Register Action C#
public class AccountController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly SignInManager<ApplicationUser> _signInManager;

    [HttpPost]
    public async Task<IActionResult> Register(RegisterViewModel model)
    {
        if (!ModelState.IsValid)
            return View(model);

        var user = new ApplicationUser
        {
            UserName = model.Email,
            Email = model.Email,
            FullName = model.FullName
        };

        var result = await _userManager.CreateAsync(user, model.Password);

        if (result.Succeeded)
        {
            await _signInManager.SignInAsync(user, isPersistent: false);
            return RedirectToAction("Index", "Home");
        }

        foreach (var error in result.Errors)
            ModelState.AddModelError(string.Empty, error.Description);

        return View(model);
    }
}

User Login

Login Action C#
[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model)
{
    if (!ModelState.IsValid)
        return View(model);

    var result = await _signInManager.PasswordSignInAsync(
        model.Email, 
        model.Password, 
        model.RememberMe, 
        lockoutOnFailure: false);

    if (result.Succeeded)
        return RedirectToAction("Index", "Home");

    ModelState.AddModelError(string.Empty, "Invalid login attempt");
    return View(model);
}

User Logout

Logout Action C#
[HttpPost]
public async Task<IActionResult> Logout()
{
    await _signInManager.SignOutAsync();
    return RedirectToAction("Index", "Home");
}

Working with Roles

Add User to Role C#
await _userManager.AddToRoleAsync(user, "Admin");

// Check if user is in role
var isAdmin = await _userManager.IsInRoleAsync(user, "Admin");

Key Takeaways

  • ASP.NET Core Identity: Complete membership system
  • IdentityUser: Base user class
  • IdentityDbContext: DbContext with Identity tables
  • UserManager: Manages users (create, update, delete)
  • SignInManager: Handles sign-in/sign-out
  • Roles: Group users with AddToRoleAsync