Cookie authentication without Identity
ASP.NET Core Identity is the full solution for user accounts, but sometimes you only need a simple sign-in, such as an admin area or users stored in an existing table. This lesson builds cookie authentication by hand with claims, sign-in, sign-out and protected actions.
- StartLogin form postedEmail and password checked against the hash
- Step 2Claims builtId, name and role
- Step 3SignInAsyncEncrypted cookie sent to the browser
- Step 4Later requestsCookie decrypted into User
- End[Authorize]Lets signed-in users through
How cookie authentication works
When the user signs in, the app creates a ClaimsPrincipal (name, id, roles) and the cookie handler encrypts it into a cookie. On every later request the handler decrypts the cookie and sets HttpContext.User. Nothing is stored on the server.
Identity adds user storage, password hashing, lockout, two-factor and more on top of this. Use it for public sign-up; use plain cookies when you already have users or need something small.
Setup
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(o =>
{
o.LoginPath = "/account/login";
o.AccessDeniedPath = "/account/denied";
o.ExpireTimeSpan = TimeSpan.FromHours(8);
o.SlidingExpiration = true;
o.Cookie.HttpOnly = true;
o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
o.Cookie.SameSite = SameSiteMode.Lax;
});
builder.Services.AddAuthorization();
app.UseAuthentication();
app.UseAuthorization();Signing in and out
Check the password against a stored hash (PasswordHasher<T> from Identity works on its own), then sign in with the user's claims.
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginModel m, string? returnUrl)
{
var user = await db.Staff.SingleOrDefaultAsync(s => s.Email == m.Email);
if (user is null || hasher.VerifyHashedPassword(user, user.PasswordHash, m.Password) == PasswordVerificationResult.Failed)
{
ModelState.AddModelError("", "Wrong email or password.");
return View(m);
}
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, user.Id.ToString()),
new(ClaimTypes.Name, user.Name),
new(ClaimTypes.Role, user.Role)
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(new ClaimsPrincipal(identity));
return LocalRedirect(Url.IsLocalUrl(returnUrl) ? returnUrl : "/");
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync();
return RedirectToAction("Index", "Home");
}Protecting pages
- [Authorize] on a controller or action requires sign-in; [Authorize(Roles = "Admin")] requires a role.
- [AllowAnonymous] opens one action inside a protected controller, such as Login.
- Read the user in code with User.Identity.IsAuthenticated and User.FindFirstValue(ClaimTypes.NameIdentifier).
- Same error message for unknown email and wrong password, so attackers cannot find valid accounts.
- Add rate limiting to the login action against password guessing.
Interview question
Where is the user's information stored with cookie authentication in ASP.NET Core?
In the cookie itself. On sign-in the claims are serialized into an authentication ticket, encrypted and signed with Data Protection keys, and sent as a cookie. Each request decrypts it back into HttpContext.User, so no server-side session is needed. Because of that, the Data Protection keys must be shared across servers and kept safe.
Want the full details? Read the official Microsoft documentation for this topic.