Section 3 of 6
Cookie Authentication
🎯 What You'll Learn
- How cookie authentication works
- Setting up cookie authentication
- Sign in and sign out
- Cookie options
- Protecting routes
How Cookie Authentication Works
Cookie authentication stores an encrypted authentication ticket in a browser cookie. The browser sends this cookie with every request to identify the user.
Setting Up Cookie Authentication
Program.cs
C#
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Logout";
options.AccessDeniedPath = "/Account/AccessDenied";
options.ExpireTimeSpan = TimeSpan.FromHours(24);
options.SlidingExpiration = true;
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
Sign In
Login Action
C#
[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model)
{
// Validate credentials (check database)
var user = await _context.Users
.FirstOrDefaultAsync(u => u.Email == model.Email);
if (user == null || !VerifyPassword(user, model.Password))
{
ModelState.AddModelError(string.Empty, "Invalid login");
return View(model);
}
// Create claims
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.Email),
new Claim(ClaimTypes.Email, user.Email),
new Claim("UserId", user.Id.ToString())
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
// Sign in
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
principal,
new AuthenticationProperties
{
IsPersistent = model.RememberMe
});
return RedirectToAction("Index", "Home");
}
Sign Out
Logout Action
C#
[HttpPost]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Index", "Home");
}
Protecting Routes
[Authorize] Attribute
C#
[Authorize]
public class DashboardController : Controller
{
public IActionResult Index()
{
return View();
}
}
Key Takeaways
- Cookie authentication: Browser-based authentication
- AddCookie(): Configure cookie options
- SignInAsync(): Create authentication cookie
- SignOutAsync(): Remove authentication cookie
- [Authorize]: Protect routes
- Best for: Traditional web apps (MVC, Razor Pages)