Cookie authentication in .NET, especially in ASP.NET Core, is a fundamental mechanism for managing user sessions and securing web applications. It stores authentication tickets inside browser cookies to track authenticated users. In this tutorial, you will learn how cookie authentication works in .NET, how to implement it step-by-step, and how to secure it properly.
Cookie Authentication is a technique where a server creates a cookie containing the user's login credentials (typically encrypted) and sends it to the client. The client then sends this cookie back to the server with every request, allowing the server to validate the user session.
Here are some reasons why cookie-based authentication is widely used in ASP.NET Core applications:
To implement cookie authentication in ASP.NET Core, you need to configure services and middleware properly. Below are the steps with complete code examples.
builder.Services.AddAuthentication("MyCookieAuth")
.AddCookie("MyCookieAuth", options =>
{
options.Cookie.Name = "MyAppAuthCookie";
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
options.SlidingExpiration = true;
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
After validating the user, issue the authentication cookie using SignInAsync.
public async Task Login(UserLoginModel model)
{
if (ModelState.IsValid && ValidateUser(model))
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, model.Username),
new Claim("FullName", "John Doe"),
new Claim(ClaimTypes.Role, "Administrator")
};
var claimsIdentity = new ClaimsIdentity(claims, "MyCookieAuth");
var authProperties = new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(20)
};
await HttpContext.SignInAsync("MyCookieAuth", new ClaimsPrincipal(claimsIdentity), authProperties);
return RedirectToAction("Index", "Home");
}
return View(model);
}
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync("MyCookieAuth");
return RedirectToAction("Login", "Account");
}
You can protect controllers or actions using the [Authorize] attribute.
[Authorize]
public class DashboardController : Controller
{
public IActionResult Index()
{
return View();
}
}
[Authorize(Roles = "Administrator")]
public IActionResult AdminPanel()
{
return View();
}
To enhance the security of your authentication cookies:
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.Strict;
| Feature | Cookie Authentication | JWT Authentication |
|---|---|---|
| Storage | Stored in browser cookies | Stored in local/session storage or cookies |
| Statefulness | Server-side stateful | Stateless |
| Use Case | Browser-based web apps | Mobile apps, SPAs, APIs |
Sliding expiration resets the cookie expiration time on each request before it expires, keeping active users logged in.
options.SlidingExpiration = true;
You can redirect users to a custom access denied page:
options.AccessDeniedPath = "/Account/AccessDenied";
public IActionResult AccessDenied()
{
return View();
}
Claims store user-specific data such as roles, email, or full name:
new Claim(ClaimTypes.Email, "user@example.com"),
new Claim("FullName", "Jane Smith")
Make sure the middleware is in the correct order:
app.UseAuthentication();
app.UseAuthorization();
Ensure HTTPS is used and domain/path settings are correct.
You can test cookie behavior using browser dev tools under the Application β Cookies tab. Check for the presence of the cookie name you configured.
Cookie authentication in .NET is a powerful and efficient way to manage user sessions in browser-based applications. It offers flexibility, performance, and integration with the .NET security ecosystem. By following best practices and understanding the configuration, you can build secure and scalable ASP.NET Core applications.
This tutorial has covered everything from basic setup to advanced security and troubleshooting for cookie authentication in .NET.
Copyrights © 2024 letsupdateskills All rights reserved