In this lesson, you will learn how to configure the authentication middleware to maintain persistent user sessions using secure, encrypted cookies.
Understanding the Cookie Flow
When a user logs in, your application creates a "ticket" that represents their identity. Instead of forcing the user to re-authenticate on every request, we store this ticket in an encrypted cookie sent back to the browser. On subsequent requests, the browser sends this cookie, and the middleware decrypts it to reconstruct the user's ClaimsPrincipal, effectively keeping them "logged in."
Configuring Persistent Cookies
To implement this in your Program.cs file, you need to register the cookie authentication scheme and configure its behavior within the builder.Services block.
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.HttpOnly = true; // Prevents JavaScript from reading the cookie
options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // Requires HTTPS
options.ExpireTimeSpan = TimeSpan.FromDays(7); // Keeps the session alive for a week
options.SlidingExpiration = true; // Resets expiration if user is active
options.LoginPath = "/Account/Login";
});
Why Encryption Matters
The AddCookie method automatically handles the encryption of the cookie payload using the data protection keys managed by ASP.NET Core. By setting HttpOnly to true, you ensure that even if your site were susceptible to cross-site scripting (XSS) attacks, malicious scripts cannot steal the user's session cookie. Setting SecurePolicy to Always guarantees that the sensitive authentication cookie is never transmitted over unencrypted HTTP connections.
When you call HttpContext.SignInAsync during your login logic, you pass these options, and the middleware takes over, serializing your claims into an encrypted token stored in the user's browser. This provides a seamless balance between security and user experience, allowing them to return to your application without re-entering credentials until the session naturally expires.
Key Takeaway: By configuring the cookie authentication middleware with encryption settings and appropriate expiration policies, you create a secure, persistent identity bridge between your server and the user's browser.