Add Session Management
Implement session management so that a user's authenticated state persists across requests.
Now that you have implemented your authentication endpoints, we'll add the ability to manage user sessions. For more details on how session management works, view our Session Management documentation.
This guide uses ASP.NET Core's built-in cookie authentication functionality to store session data in cookies.
Do you need session management?
Short answer: Yes.
While session management is technically optional, it's very strongly recommended. Without session management, the user's authenticated state would be lost on each each request and they'd have to continually reauthenticate.
Enable Cookie Authentication Middleware
This guide implements sessions using cookies. This approach stores all session data encrypted inside a cookie, so no server-side storage is necessary.
To enable session cookies, you'll need to configure the Authentication Middleware service to support cookie authentication using the AddAuthentication
and AddCookie
methods. Likewise, you'll need to enable the Authentication Middleware by calling the UseAuthentication
method.
// Program.cs
using Microsoft.AspNetCore.Authentication.Cookies;
using Wristband.AspNet.Auth;
...
// Configure the Authentication Middleware to support cookie authentication.
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "session";
options.Cookie.HttpOnly = true;
// If your server doesn't support HTTPS you'll need to set this to
// CookieSecurePolicy.None instead.
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.Strict;
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
// Return a 401 error code to clients instead of redirecting.
options.UseWristbandApiStatusCodes();
});
var app = builder.Build();
// Enable the Authentication Middleware. This method must be called before
// mapping any endpoints that require authentication.
app.UseAuthentication();
...
Now that cookie authentication is enabled, the session for each authenticated user will be accessible from the HttpContext.User
object throughout your endpoints.
Updated about 24 hours ago
Next, let's enhance the authentication routes you previously created to add session management logic.