Add Session Management
Implement session management to securely manage user sessions and store authentication tokens.
Now you'll need to implement the ability to securely manage user sessions and store tokens between requests. For more details on how session management works, view our Session Management documentation .
While this guide uses cookie authentication (storing encrypted session data in cookies), consider server-side sessions if you need centralized session management.
Do you need session management?
Short answer: Yes.
While session management is technically optional, it's very strongly recommended for most applications. Only skip session management if your existing architecture makes implementation impractical.
Add Cookie Authentication for Stateless Sessions
This guide implements cookie authentication, where user identity is encrypted and stored directly in the cookie. This stateless approach requires no server-side storage and includes user info in each request.
Configure cookie authentication to enable encrypted, cookie-based sessions:
// Program.cs
using Microsoft.AspNetCore.Authentication.Cookies;
using Wristband.AspNet.Auth;
...
// Add cookie session for authenticated users
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "session";
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.Strict;
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
// Return 401 errors codes to client instead of redirects.
options.UseWristbandApiStatusCodes();
});
var app = builder.Build();
// This middleware must be added before any endpoints that require authentication.
app.UseAuthentication();
...
Now the session for each authenticated user will be accessible from the HttpContext on the User
object throughout your routes.
Updated 8 days ago
Next, let's enhance the auth routes to add session management logic. We'll also introduce a new Session endpoint for loading session data into your frontend.