Aspnet Auth
title: ASP.NET Core Authentication — Complete Guide to Identity & Auth description: 'Learn ASP.NET Core authentication: Identity framework, cookie auth, external providers (Google, Facebook), policy-based authorization, claims, and role management.' date: 2026-06-28 lastmod: 2026-06-28 weight: 24 tags: [backend, aspnet]
ASP.NET Core authentication verifies user identity through cookies, JWT tokens, or external providers, with ASP.NET Core Identity providing user registration, login, and role management.
## What You'll Learn
By the end of this tutorial, you'll configure ASP.NET Core Identity, implement registration and login, manage roles and claims, use cookie and JWT authentication, and integrate external providers.
## Real-World Use
A membership site uses ASP.NET Core Identity with cookie auth for the web app and JWT for the mobile API. Users register, verify email, and access protected resources based on roles.
## Authentication Learning Path
```mermaid
flowchart LR
A[Migrations] --> B[Auth]
B --> C[JWT]
C --> D[Web API]
D --> E[Minimal API]
B --> F{You Are Here}
style F fill:#f90,color:#fff
Identity Setup
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore
dotnet add package Microsoft.AspNetCore.Identity.UI
// DbContext
public class AppDbContext : IdentityDbContext<IdentityUser>
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
}
// Program.cs
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(connStr));
builder.Services.AddDefaultIdentity<IdentityUser>(options =>
{
options.SignIn.RequireConfirmedAccount = true;
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>();
var app = builder.Build();
app.MapRazorPages(); // Identity UI pages (Register, Login, etc.)
Registration and Login
[ApiController]
[Route("api/auth")]
public class AuthController : ControllerBase
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
public AuthController(UserManager<IdentityUser> um, SignInManager<IdentityUser> sim)
{
_userManager = um;
_signInManager = sim;
}
[HttpPost("register")]
public async Task<IActionResult> Register(RegisterDto dto)
{
var user = new IdentityUser { UserName = dto.Email, Email = dto.Email };
var result = await _userManager.CreateAsync(user, dto.Password);
if (!result.Succeeded)
return BadRequest(result.Errors);
await _userManager.AddToRoleAsync(user, "User");
return Ok(new { Message = "Registration successful" });
}
[HttpPost("login")]
public async Task<IActionResult> Login(LoginDto dto)
{
var result = await _signInManager.PasswordSignInAsync(
dto.Email, dto.Password, dto.RememberMe, lockoutOnFailure: false);
if (!result.Succeeded)
return Unauthorized();
return Ok(new { Message = "Login successful" });
}
}
Policy-Based Authorization
// Program.cs
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdmin", policy => policy.RequireRole("Admin"));
options.AddPolicy("CanManageProducts", policy =>
policy.RequireClaim("Permission", "ManageProducts"));
options.AddPolicy("Over18", policy =>
policy.Requirements.Add(new MinimumAgeRequirement(18)));
});
// Usage
[Authorize]
public class AccountController : ControllerBase
{
[Authorize(Roles = "Admin")]
public IActionResult AdminDashboard() { ... }
[Authorize(Policy = "CanManageProducts")]
public IActionResult ManageProducts() { ... }
}
External Login Providers
builder.Services.AddAuthentication()
.AddGoogle(options =>
{
options.ClientId = builder.Configuration["Google:ClientId"] ?? "";
options.ClientSecret = builder.Configuration["Google:ClientSecret"] ?? "";
})
.AddFacebook(options =>
{
options.AppId = builder.Configuration["Facebook:AppId"] ?? "";
options.AppSecret = builder.Configuration["Facebook:AppSecret"] ?? "";
})
.AddMicrosoftAccount(options =>
{
options.ClientId = builder.Configuration["Microsoft:ClientId"] ?? "";
options.ClientSecret = builder.Configuration["Microsoft:ClientSecret"] ?? "";
});
Common Mistakes
1. Not Using Password Hashers
Identity automatically hashes passwords. Never store plain text or use custom hashing.
2. Ignoring Account Lockout
Without lockout, attackers brute force passwords. Enable lockoutAfterFailedAttempts in Identity options.
3. Exposing Identity User to API
IdentityUser contains internal data (PasswordHash). Map to a DTO before returning.
4. Not Configuring Cookie Settings
Set HttpOnly, SameSite, and Secure flags on auth cookies to prevent XSS and CSRF.
5. Missing Email Confirmation
Without email confirmation, anyone can register with fake emails. Require ConfirmedAccount.
Practice Questions
1. What is ASP.NET Core Identity?
A membership system that provides user registration, login, password management, roles, and claims.
2. How do you protect an action with authorization?
Use the [Authorize] attribute. Optionally specify roles or policies.
3. What are claims in ASP.NET Core?
Key-value pairs about the user (email, name, permissions). Used for authorization decisions.
4. How do you integrate Google login?
Add AddGoogle() to the auth builder. Configure ClientId and ClientSecret from Google Cloud Console.
5. Challenge: Create a complete auth system with registration, login, and admin-only area.
[Authorize(Roles = "Admin")]
[ApiController]
[Route("api/admin")]
public class AdminController : ControllerBase
{
[HttpGet("users")]
public async Task<ActionResult<List<UserDto>>> GetAllUsers()
{
var users = await _userManager.Users.ToListAsync();
return Ok(users.Select(u => new UserDto(u.Id, u.Email ?? "")));
}
}
FAQ
Mini Project: Identity with Registration and Login
Set up ASP.NET Core Identity with custom registration and login endpoints.
builder.Services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>();
// Registration endpoint creates user with email and password
// Login endpoint validates credentials and returns success/failure
// Protected endpoints use [Authorize] attribute
What's Next
ASP.NET Core JWT ASP.NET Core Web API
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro