HTTP requests are independent, so applications need a mechanism to associate subsequent requests with an authenticated user. Three common designs are server-side sessions, signed client-side session cookies, and bearer tokens.
Server-side sessions
After authentication, the server creates a session record and gives the browser an opaque, unpredictable session ID, usually in a cookie. Later requests carry that ID, and the server looks up the session. Logout or expiration invalidates the server-side record.
This supports straightforward revocation, but a multi-instance deployment needs a shared session store or another consistent routing strategy. Rotate session IDs after authentication to reduce session fixation risks.
Client-side session cookies
The server can place session data in a signed cookie instead of storing a record for every session. A signature protects integrity, not confidentiality; encrypt sensitive data if it must be stored there. Cookie size limits and revocation of already-issued cookies are important tradeoffs.
Cookies have domain and path rules. For authentication cookies, use HTTPS and appropriate
Secure, HttpOnly, and SameSite settings; protect state-changing requests against CSRF as required by the application.Bearer tokens
Clients can send a token in an
Authorization: Bearer header. Tokens may be opaque and verified against server-side state, or self-contained such as signed JWTs. A JWT is a token format, not a guarantee of security: validate its signature, allowed algorithms, issuer, audience, and expiration as appropriate.Anyone who obtains a bearer token can generally use it until it expires or is revoked. Use short lifetimes, secure storage, TLS, and an appropriate revocation or rotation strategy. Avoid exposing tokens in URLs or logs.
Choosing a design
Server-side sessions simplify revocation; signed cookies reduce session-store lookups; bearer tokens can suit APIs and non-browser clients. None is automatically safest. Cookie-based credentials need CSRF defenses, and all approaches need protections against credential theft, XSS, and transport interception.
✦ 卷终 · 柯航存卷 ✦