Lesson 3 of 8
ASP.NET Core Identity - Setup & UserManager
ASP.NET Core Identity manages users, passwords, roles, claims, and external logins. UserManager<T> provides user operations (create, find, change password). SignInManager<T> handles sign-in logic including lockout and two-factor authentication.
Identity Configuration & Custom ApplicationUser
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
// ━━ Extend IdentityUser with custom fields ━━
public class ApplicationUser : IdentityUser
{
[MaxLength(100)] public string FirstName { get; set; } = "";
[MaxLength(100)] public string LastName { get; set; } = "";
public string? ProfilePictureUrl { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public bool IsActive { get; set; } = true;
public string FullName => $"{FirstName} {LastName}".Trim();
}
// ━━ Identity DbContext (or integrate with AppDbContext) ━━
public class IdentityAppDbContext : IdentityDbContext<ApplicationUser>
{
public IdentityAppDbContext(DbContextOptions<IdentityAppDbContext> options) : base(options) { }
}
// ━━ Registration ━━
builder.Services
.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
// Password rules
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequiredLength = 8;
// Lockout - prevent brute force
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
// Email confirmation required
options.SignIn.RequireConfirmedEmail = true;
// User settings
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<IdentityAppDbContext>()
.AddDefaultTokenProviders(); // for email confirm / password reset tokens
// ━━ Registration flow ━━
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] RegisterRequest request)
{
var user = new ApplicationUser
{
UserName = request.Email,
Email = request.Email,
FirstName = request.FirstName,
LastName = request.LastName,
};
var result = await userManager.CreateAsync(user, request.Password);
if (!result.Succeeded)
{
return BadRequest(new ValidationProblemDetails
{
Errors = result.Errors
.GroupBy(e => e.Code)
.ToDictionary(g => g.Key, g => g.Select(e => e.Description).ToArray())
});
}
// Assign default role
await userManager.AddToRoleAsync(user, "User");
// Generate email confirmation token
var token = await userManager.GenerateEmailConfirmationTokenAsync(user);
// Send email with: /api/auth/confirm-email?userId={user.Id}&token={Uri.EscapeDataString(token)}
return Ok(new { message = "Account created. Please check your email to confirm." });
}
// ━━ Password reset flow ━━
[HttpPost("forgot-password")]
public async Task<IActionResult> ForgotPassword([FromBody] ForgotPasswordRequest req)
{
var user = await userManager.FindByEmailAsync(req.Email);
if (user is null) return Ok(); // don't reveal if email exists
var token = await userManager.GeneratePasswordResetTokenAsync(user);
// Send reset link: /api/auth/reset-password?token=...&email=...
return Ok(new { message = "If that email exists, a reset link has been sent." });
}
record RegisterRequest(string Email, string Password, string FirstName, string LastName);
record ForgotPasswordRequest(string Email);
UserManager<ApplicationUser> userManager = null!;Tip
Tip
Practice ASPNET Core Identity Setup UserManager in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of ASPNET Core Identity Setup UserManager from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with ASPNET Core Identity Setup UserManager is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?