If you own the backend and only need to keep users signed in to your app, start with an opaque session ID in an HttpOnly cookie. If the app uses OAuth to call upstream APIs, consider keeping those tokens on the server behind a backend-for-frontend. When the browser must hold an access token, page memory limits how long it persists. The examples below show what each choice protects and where the backend still has work to do.
1. Why HTTP needs a credential#
A request arrives with its own method, URL, headers, and body. The server needs a way to connect that request to an identity even if it reaches a different process from the one that handled sign-in. Authentication establishes who is making the request. Authorization decides what that identity may do. The backend checks both before giving access to protected data.
With a server-side session, the browser sends an opaque ID that the backend looks up. With a signed access token, an API can verify the token and its claims using the issuer’s key and policy. The placement and transport of the credential determine what the browser sends automatically and what page scripts can see. OWASP Session Management
Step 1 of 2
This protected resource requires an identity. The request arrives with no session cookie or Authorization header.
2. What a JWT actually contains#
A JSON Web Token carries a set of claims. The compact signed form in this example has three parts. The header identifies the signing algorithm and can describe the token type. The payload contains the claims. The signature binds the encoded header and payload to a trusted key. Base64url makes those bytes convenient to transport, and anyone with the signed token can decode its contents. Encryption requires a separate construction, such as JWE. RFC 7519
A resource server chooses the algorithms and keys it trusts, verifies the signature, checks the expected issuer (iss) and audience (aud), and enforces expiration (exp) and earliest valid time (nbf) where applicable. The subject (sub) identifies the principal in the issuer’s context. Issued-at (iat) records when issuance happened and can matter to local policy. The token’s type, purpose, and application claims determine which validation rules apply. The resource still needs to authorize the operation. RFC 8725
An access token is presented to a resource server. A refresh token is presented to the authorization server to obtain new access tokens. Either can be opaque, and an app’s own session ID can simply identify a server-side record. JWT describes a format. Issuance, storage, transport, and revocation each need an architecture. RFC 6749
Compact signed JWT
eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJyZWFkZXItNDIiLCJpc3MiOiJodHRwczovL2lkZW50aXR5LmV4YW1wbGUudGVzdCIsImF1ZCI6ImpvdXJuYWwtZXhhbXBsZSIsImlhdCI6MTgwMDAwMDAwMCwibmJmIjoxODAwMDAwMDAwLCJleHAiOjE4MDAwMDAzMDAsInNjb3BlIjoicHJvZmlsZTpyZWFkIn0.JuEDtB38c52Kl70nKUdoJnTMd7PHpkQh7KeZuRQBHCWBSc7Pk1nKO9Weycs-2_NxD2xScvZO75oL-y5ABsxTdQThe inspector serializes the JSON before verification. Try changing sub or scope.
Decoded claim meanings
sub- Subject identifier
iss- Trusted issuer
aud- Intended recipient
exp- Expiration time
iat- Issued-at time
nbf- Earliest valid time
scope- Illustrative permission
Signature: Signature verification runs in the browser.
Claim checks: The issuer, audience, and example time checks pass.
3. Where credentials can live#
Start by separating where the value lives from who sends it. A cookie goes with eligible requests according to browser policy. A value in browser storage or page memory has to be attached by the client. A BFF uses both transports at different boundaries. The browser sends its app session cookie to the BFF, which presents an access token to the upstream API.
| Strategy | What is held and where |
|---|---|
| Local Storage | A persistent value available to scripts running in the origin |
| Session Storage | A value available to scripts in the tab’s page session |
| IndexedDB | A durable record in an origin-scoped browser database |
| JavaScript-readable cookie | A scoped cookie that eligible page code can read |
| HttpOnly cookie | A scoped cookie whose value the browser withholds from page code |
| Page memory | A value held by the current page runtime |
| Dedicated worker memory | A value held by a worker with an explicit messaging boundary |
| Backend-for-Frontend | Upstream tokens on the server and an opaque app session cookie in the browser |
| Server-side session | Server-side session state and an opaque identifier in the browser |
Cookies follow configured lifetimes and browser policy. Closing a single tab usually leaves eligible cookies available to other tabs. Persistent browser storage can also be cleared, partitioned, or evicted. A legitimate session can end while its cached value still exists, which makes server enforcement essential. OWASP Session Management, OWASP HTML5 Security
Step 1 of 7
The browser sends a fictional sign-in to the backend over HTTPS.
Trade-offs for Local Storage
- Credential location
- Origin Local Storage
- JavaScript access
- Direct value access
- Browser attaches it
- Explicit Authorization header
- Persistence
- Persists until cleared or evicted
- Reload
- Credential generally remains
- Close tab
- Credential can survive closing one tab
- Other tabs
- Shared within an origin and storage partition
- Direct credential theft under XSS
- Same-origin script can read it
- Authenticated actions under XSS
- Possible while the compromised page can invoke authenticated behavior
- CSRF exposure
- This header is client-added. Check any separate cookie endpoints.
- Logout and revocation
- Clear the local copy. A copied bearer remains usable until expiry or server rejection.
- Implementation complexity
- Low client complexity
- User experience
- Survives reloads and browser restarts in normal use
- Appropriate use
- Keep ordinary preferences here. Avoid storing session IDs and sensitive bearer credentials.
4. Local Storage makes a credential easy to retrieve#
Persistence makes reload simple. After the new page starts, it can retrieve the bearer and attach it to the request. That same access remains available to malicious JavaScript executing within the origin. The value can remain there after the page that received it is gone, and Local Storage has no equivalent to HttpOnly.
The example below illustrates a discouraged production pattern. It uses fictional data and makes no network request.
const exampleAccessToken = 'fictional-classroom-value';
localStorage.setItem('example-access-token', exampleAccessToken);
const requestHeaders = {
Authorization: `Bearer ${localStorage.getItem('example-access-token')}`,
};
Deleting the stored value clears that browser’s copy. A copied bearer can still be accepted until expiration or an effective server rejection, which is why storing sensitive bearer credentials in persistent script-readable storage increases the consequences of XSS. OWASP HTML5 Security, RFC 9700
Step 1 of 7
The browser sends a fictional sign-in to the backend over HTTPS.
Simulation event log
Play or advance the timeline to see recorded events.
5. Session Storage, page memory, and workers#
Session Storage usually survives a reload within the current page session. A new independent tab has a separate page session, although a tab with an opener can start with a copy. Same-origin JavaScript in the affected tab can read the value. In the examples, closing the tab ends its session and opening a new independent tab starts with empty storage. WHATWG Web Storage
Page memory disappears when the page is replaced in a normal reload. That reduces persistence, while code running in the same origin can still read values that are exposed to it, intercept their use, or use whatever authenticated functionality the page provides. A dedicated worker can keep the value out of the page’s runtime if it never sends the value back. Its message interface can still be used from a compromised page. OWASP Session Management, RFC 10017
Credential present and usable.
Credential absent in the new runtime or tab.
Credential absent in the new runtime or tab.
6. Cookies and HttpOnly#
The server issues a cookie with Set-Cookie. The browser decides whether to store it and whether it belongs on a later request. HttpOnly prevents direct JavaScript reads, while the browser can still use the cookie in eligible requests, including ones initiated by same-origin script.
| Attribute | What it changes |
|---|---|
HttpOnly |
Withholds the value from page JavaScript |
Secure |
Restricts transmission to secure connections, with browser treatment of localhost as a special case |
SameSite=Strict |
Excludes cross-site requests in the modeled contexts |
SameSite=Lax |
Allows eligible top-level cross-site navigations using safe methods |
SameSite=None |
Permits cross-site use when combined with Secure, subject to browser policy |
Path |
Limits request paths that receive the cookie |
Domain |
Extends scope to the specified domain and eligible subdomains. Omit it for a host-only cookie |
Max-Age and Expires |
Control lifetime. Max-Age takes precedence when both are present |
__Host- |
Requires Secure, Path=/, and no Domain on browsers that enforce the prefix |
Two origins can belong to the same site. That distinction affects SameSite, while fetch credentials and CORS use origins. The playground issues the cookie over HTTPS and models explicit SameSite values. Use a top-level navigation to compare Secure cookies on HTTP and HTTPS. An HTTPS page cannot make a background fetch to that HTTP target. Actual browsers can apply additional privacy rules or restrictions on cross-site cookies. MDN Set-Cookie, Fetch Standard
Set-Cookie: __Host-session=<opaque-id>; Path=/; Secure; HttpOnly; SameSite=Lax
A suitable SameSite policy helps reduce CSRF exposure. Protect state-changing endpoints with a server-side control such as a CSRF token or appropriate origin validation. Keep safe methods free of state changes and choose a cookie policy that fits your sign-in flows. OWASP CSRF Prevention
Set-Cookie: session=<fictional>; Path=/; SameSite=Lax; HttpOnly; Secure Stored: Yes · Readable by eligible page script: No
Cookie sent: Yes. The cookie is eligible for this request.
Step 1 of 4
The HTTPS origin app.example.test returns the sample Set-Cookie header.
7. XSS and CSRF ask different questions#
XSS begins when unauthorized script runs within the app’s origin. It inherits the access that the page gives its own scripts. HttpOnly can protect the cookie’s value while leaving the browser able to make an authenticated request. Use context-appropriate output encoding, safe DOM APIs, and a carefully deployed Content Security Policy as defense in depth. OWASP XSS Prevention
CSRF starts outside the app. The question is whether the browser includes credentials the backend will accept when the user never intended to make the request. An external site need not read the response for a state change to occur. CORS and CSRF defenses serve different purposes. Apply backend checks to state-changing cookie-authenticated endpoints. OWASP CSRF Prevention
Replay starts from the assumption that a credential was already copied. If the resource server still accepts that bearer, possession may be enough. A short lifetime reduces the window of use. Sender constraints, session checks, or a revocation mechanism can change whether a copied credential still works. The lab models outcomes with fictional events. RFC 9700
Direct credential exposure: Protected from direct reads
Authenticated action: Possible
The page cannot directly read the isolated credential in this design. Script can still ask the app or browser to make an authenticated request.
Step 1 of 4
The modeled script is already running within the application’s origin.
Simulation event log
Play or advance the timeline to see recorded events.
Request and response details
Credential transport: Eligible browser cookie
Result: The modeled backend accepts the action.
What remains: Output encoding, safe DOM APIs, and a carefully deployed CSP reduce injection risk. Each backend operation still needs authorization.
8. Access and refresh credentials age differently#
An access token is used repeatedly at a resource server, so short validity limits how long a copied token can be used. A refresh token can issue new access tokens and deserves tighter handling. Refresh rotation replaces the previous refresh credential. If the old credential appears again, an authorization server can detect reuse and revoke the active token family. For OAuth public clients, RFC 9700 requires refresh tokens to be sender-constrained or use rotation. RFC 9700
Handle concurrent refreshes deliberately. The simulation coalesces two refresh attempts into one exchange so both callers can use the result. A real system needs coordination appropriate to its client instances and server design. Reusing a rotated token can otherwise resemble theft and end the session.
An idle deadline bounds inactivity. An absolute deadline caps the session even while it stays active. Logout can end the app session and revoke its refresh credentials, while a resource server that validates access JWTs independently can still accept one until expiration. Model effective revocation at the resource server if the app needs a faster cutoff. The five-minute access lifetime and the session deadlines below are illustrative. OWASP Session Management, RFC 7009
Minute 0 · A1: Valid until minute 5 · Refresh family: active
Sign-in issues access token A1 and refresh credential R1.
Idle deadline: minute 15. Absolute deadline: minute 60.
Step 1 of 3
Sign-in creates an access token and a refresh credential.
Lifecycle history
- Sign-in issues access token A1 and refresh credential R1.
9. Four architectures to compare#
Browser-only SPA. When a browser OAuth client is required, use Authorization Code with PKCE. Keep access tokens in memory, present them with an Authorization bearer header, and follow the authorization server’s refresh requirements. Reload discards the current token. The app can restore the session only through a supported flow. Malicious JavaScript in the browser remains a concern. RFC 10017
Cookie-based backend. A traditional backend starts a session and issues a Secure, HttpOnly cookie. It authorizes requests using session state and applies CSRF defenses. An opaque ID gives the backend a direct way to end the session. If the cookie contains a JWT instead, the browser behavior is similar, but the backend must verify the JWT and decide how to invalidate it before expiry. OWASP Session Management, RFC 8725
Memory with a refresh cookie. A trusted backend can issue a Secure, HttpOnly refresh cookie and provide a dedicated refresh endpoint. After reload, the browser calls that endpoint with its eligible cookie and gets a new access token into memory. Apply CSRF defenses to that endpoint, rotate the refresh credential where appropriate, and design for reuse detection. This is a particular app design that depends on the backend and identity provider. The browser still handles the access token.
Backend-for-Frontend. A BFF retains upstream OAuth tokens, attaches them to requests it proxies, and handles upstream refresh. The browser holds an opaque Secure, HttpOnly session cookie. This keeps upstream credentials out of frontend JavaScript and can be a good fit for security-sensitive apps with a trusted backend. It adds a proxy, server-side lifecycle management, and CSRF defenses. Same-origin XSS can still misuse an active browser session. RFC 10017
The browser is the OAuth client. It holds the access token in memory and calls the API directly. Refresh depends on the authorization server’s policy.
Step 1 of 5
The browser uses Authorization Code with PKCE and holds the issued access token in memory.
Simulation event log
Play or advance the timeline to see recorded events.
10. Compare storage decisions side by side#
Pick two strategies and compare how each handles a reload, a same-origin script, and a state-changing request. A strategy can prevent a direct credential read while leaving opportunities to act as the user. Expiration and revocation are separate controls that can shorten the useful life of a copied credential.
2 selected.
| Property | Local Storage | HttpOnly cookie |
|---|---|---|
| Credential location | Origin Local Storage | Browser cookie jar |
| JavaScript access | Direct value access | Value isolated from page script |
| Browser attaches it | Explicit Authorization header | Automatically on eligible requests |
| Persistence | Persists until cleared or evicted | Follows cookie/session settings |
| Reload | Credential generally remains | Credential generally remains |
| Close tab | Credential can survive closing one tab | Credential can survive closing one tab |
| Other tabs | Shared within an origin and storage partition | Shared where host, path, and cookie policy allow |
| Direct credential theft under XSS | Same-origin script can read it | Direct page reads are blocked in this design |
| Authenticated actions under XSS | Possible while the compromised page can invoke authenticated behavior | Possible while the compromised page can invoke authenticated behavior |
| CSRF exposure | This header is client-added. Check any separate cookie endpoints. | Eligible cross-site cookies can accompany a request. Apply server-side defenses. |
| Logout and revocation | Clear the local copy. A copied bearer remains usable until expiry or server rejection. | Server can invalidate an opaque ID. A stateless JWT needs separate revocation or short expiry. |
| Implementation complexity | Low client complexity | Cookie scoping, credential validation, and CSRF defenses |
| User experience | Survives reloads and browser restarts in normal use | Session can continue on reload |
| Appropriate use | Keep ordinary preferences here. Avoid storing session IDs and sensitive bearer credentials. | Use a secure cookie for first-party sessions with server-side defenses. |
Why separate theft, authenticated action, and replay?
HttpOnly can stop a direct read even when the browser still acts for the user. Short validity and server-side revocation can help limit what happens after an independent disclosure. These are different properties.
What changes when the cookie contains a JWT?
Browser attachment and JavaScript visibility follow cookie rules. Server-side invalidation depends on whether the backend checks session state, revocation, or token expiry.
11. Choose an architecture for your application#
Start with the credentials your API actually needs. If a browser only needs an app session, an opaque cookie backed by a server record is usually enough. If upstream OAuth is required and you can run a trusted backend, a BFF keeps the upstream tokens there. If the browser must call a protected API directly, memory-only storage limits persistence and leaves you with a session-restoration decision.
If the frontend and backend live on separate origins, establish whether they also live on separate sites. That distinction changes the cookie rules and how much you can rely on a cross-site session design. Check the browser and identity provider policies for your deployment. RFC 10017, MDN Set-Cookie
Store the session record on your backend and use a Secure, HttpOnly cookie for the ID. Invalidate the record at logout.
- Same-origin deployment simplifies cookie scope. Maintain backend CSRF and authorization checks.
- Use a bounded session and decide what reload and browser restart should do.
- Apply least privilege and keep credential lifetimes bounded.
12. Knowledge check and implementation checklist#
0 of 8 answered.
- Pick the smallest credential and architecture that support the app. Start with an opaque server session if the app only needs first-party sign-in.
- Keep sensitive credentials out of durable script-readable browser storage. Document what reload, tab closure, expiration, and logout do.
- Serve credentials over HTTPS. For cookie-based sessions, choose Secure, HttpOnly, host and path scope, lifetime, and SameSite deliberately.
- Protect against XSS at the rendering boundary and CSRF on state-changing cookie-authenticated endpoints.
- Validate the credential and enforce authorization on the backend. For JWTs, allowlist algorithms and verify the signature, issuer, audience, expiry, and applicable claims.
- Set bounded session and access-token lifetimes. Design refresh rotation, reuse detection, and concurrency handling when the chosen flow uses them.
- Decide which credentials logout revokes and how quickly every resource server enforces revocation.