Skip to content
Commitwise
Menu
Networking

Cookies, CORS and sessions

How a website remembers who you are and which other sites may talk to it. Covers Set-Cookie and its attributes, HttpOnly, Secure and SameSite (Lax by default), sites vs origins, the same-origin policy, CORS headers, simple requests vs preflights, credentials, the misconfigurations that leak data, server sessions vs tokens, where to keep tokens on the web and on mobile, and CSRF.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

HTTP forgets everything between requests. Logging in, keeping a cart and staying signed in for a month all depend on something the client sends back each time, usually a cookie or a token. At the same time, the browser has to stop other websites from using that login: a page on evil.example mustn’t be able to read your bank’s API as you.

Those two jobs meet in three topics that interviews love and production gets wrong: cookies and their attributes, the same-origin policy with its controlled exception CORS, and how sessions and tokens are stored and protected. This lesson covers all three, for the web and for mobile apps. It builds on HTTP: methods, status codes and headers and TLS and HTTPS.

New to some of these? Open what you need, or skip ahead.

Basics:Headers

Requests and responses carry headers. Servers set cookies with the Set-Cookie response header; browsers send them back in the Cookie request header. CORS is also just a handful of headers. See HTTP: methods, status codes and headers.

Basics:Domain names

api.shop.example is a subdomain of shop.example. The part a company registers, like shop.example or shop.co.uk, is the registrable domain; browsers use it to decide what counts as the same site. See DNS.

Part Not started

Cookies

A cookieCookieA small name-value pair a server stores in the browser with Set-Cookie, which the browser sends back on matching requests.Open in glossary → is a small name-value pair that a server asks the browser to store and send back:

HTTP/1.1 200 OK
Set-Cookie: session=8f2c91d4; Path=/; Max-Age=2592000; Secure; HttpOnly; SameSite=Lax

GET /orders HTTP/1.1
Host: shop.example
Cookie: session=8f2c91d4

From then on, every request to shop.example includes Cookie: session=8f2c91d4, and the server knows who’s asking. The attributes after the value control the cookie:

AttributeMeaning
Max-Age=2592000 or Expires=…Keep it for 30 days. Without either, it’s deleted when the browser session ends.
Domain=shop.exampleAlso send it to subdomains like api.shop.example. Without it, only the exact host that set it gets it back.
Path=/Send it for every path on the site.
SecureOnly send it over HTTPS.
HttpOnlyJavaScript can’t read it through document.cookie, so a malicious script injected into the page can’t steal it.
SameSite=LaxDon’t send it on requests that other sites trigger in the background (more below).

SameSite decides what happens when a request is caused by a different site:

  • Strict: never sent on cross-site requests, not even when the user clicks a link from another site to yours (they arrive logged out).
  • Lax: sent when the user navigates to your site (clicking a link), but not on cross-site background requests (fetch, images, forms posted from another site).
  • None: always sent; requires Secure. Needed for cookies used inside other sites, like an embedded widget.

A cookie without SameSite is treated as Lax by modern browsers. For a login session, the safe default is Secure; HttpOnly; SameSite=Lax.

  • Site vs origin: an origin is scheme + host + port (https://api.shop.example:443); a site is scheme + registrable domain (https://shop.example, using the Public Suffix List). SameSite is about sites, so api.shop.example and www.shop.example are same-site; CORS is about origins, so they’re cross-origin.
  • Lax by default (Chrome since 2020, others followed) with a quirk: cookies set without any SameSite attribute in the last two minutes are still sent on top-level cross-site POST navigations (“Lax+POST”), to keep some sign-in flows working. An explicit SameSite=Lax doesn’t get that exception.
  • Prefixes: __Host-session must be Secure, Path=/, and have no Domain, so a compromised or malicious subdomain can’t overwrite it; __Secure- only requires Secure. Use __Host- for session cookies.
  • Third-party cookies: Safari and Firefox block them by default; Chrome still allows them: in 2025 Google dropped its plan to phase them out and retired most Privacy Sandbox APIs. Partitioned (CHIPS) cookies are keyed by the top-level site, for embeds that need state without cross-site tracking.
  • Limits: about 4 KB per cookie, dozens per domain, and every cookie rides on every matching request, including static assets, so keep cookies small and serve assets from a cookieless domain or path.
  • Native apps: HTTPCookieStorage with URLSession on iOS handles cookies automatically; OkHttp needs a CookieJar. Most mobile APIs use tokens in Authorization instead, with no cookie rules at all.

Predict the output

A page on http://127.0.0.1:8097 receives the four Set-Cookie headers below, then runs document.cookie. What does it get?

Set-Cookie: plain=1
Set-Cookie: lax=1; SameSite=Lax
Set-Cookie: none=1; SameSite=None; Secure
Set-Cookie: ho=1; HttpOnly
// Android: OkHttp sends no cookies unless you give it a CookieJar
val client = OkHttpClient.Builder()
    .cookieJar(JavaNetCookieJar(CookieManager()))   // in memory; persist it for real apps
    .build()
// Express: a session cookie with the safe attributes
res.cookie('__Host-session', sessionId, {
  httpOnly: true,
  secure: true,
  sameSite: 'lax',
  path: '/',
  maxAge: 30 * 24 * 3600 * 1000,   // milliseconds in Express
});

// logging out: overwrite with the same name and attributes, already expired
res.clearCookie('__Host-session', { httpOnly: true, secure: true, sameSite: 'lax', path: '/' });
Spot the bugLogging in

Tap the line with the bug.

app.post('/login', async (req, res) => {
  const user = await checkPassword(req.body.email, req.body.password);
  if (!user) return res.status(401).end();
  const sessionId = await sessions.create(user.id);
  res.set('Set-Cookie', 'session=' + sessionId + '; Path=/; Max-Age=2592000');
  res.redirect('/');
});

Deep diveSubdomains, cookie scope and session fixationInterview favorite

“Our marketing site at blog.shop.example runs a third-party CMS. Is the shop’s session at risk?” This tests whether you know how cookies cross subdomains.

  • Reading: a cookie set by shop.example with Domain=shop.example is sent to every subdomain, including blog.shop.example. If the CMS is compromised, or logs request headers, the session leaks. A cookie set without Domain is host-only and goes nowhere else. So: never set Domain on session cookies unless you need it.
  • Writing: any subdomain can set a cookie for the parent domain. JavaScript on blog.shop.example can run document.cookie = "session=attacker-id; Domain=shop.example; Path=/". If the shop accepts a session ID it didn’t just issue, the user logs in to the attacker’s session (session fixation), or a shadowing cookie breaks login. The __Host- prefix stops this: the browser rejects any __Host- cookie that has a Domain attribute or lacks Secure, so subdomains can’t plant one.
  • SameSite doesn’t help here: blog.shop.example is the same site as shop.example, so its requests carry Lax and even Strict cookies. Same-site isn’t same-trust.
  • Takeovers: a dangling DNS record (old.shop.example CNAME to a deleted cloud bucket that someone else can claim) gives an attacker a subdomain, with all the powers above.

Recommendations: __Host- session cookies, regenerate session IDs on login and privilege changes, host untrusted content on a separate registrable domain (that’s why user content lives on domains like githubusercontent.com), and audit DNS for dangling records.

  • Origin = scheme + host + port (CORS); site = scheme + registrable domain (SameSite). Subdomains are same-site.
  • Session cookie: __Host- prefix, Secure, HttpOnly, SameSite=Lax or Strict, no Domain, regenerate on login.
  • Default is Lax (with the 2-minute Lax+POST exception for cookies without the attribute). None requires Secure; third-party cookies blocked in Safari and Firefox; Partitioned for embeds.
  • Native: HTTPCookieStorage automatic on iOS, OkHttp needs a CookieJar; most mobile APIs use bearer tokens.
Set-Cookie: __Host-session=8f2c91d4; Path=/; Max-Age=2592000; Secure; HttpOnly; SameSite=Lax

Check this part

  1. Which attribute stops JavaScript on the page from reading a cookie?

  2. A cookie has no SameSite attribute. How do modern browsers treat it?

  3. Are api.shop.example and www.shop.example the same site? The same origin?

  4. What does the __Host- prefix guarantee?

A server sets a cookie with Set-Cookie and the browser sends it back on matching requests. Attributes decide its life and reach: Expires/Max-Age, Domain, Path, Secure (HTTPS only), HttpOnly (hidden from JavaScript) and SameSite (whether cross-site requests carry it). Browsers treat a cookie without SameSite as Lax, so cross-site fetches don't send it. Session cookies should be Secure, HttpOnly and SameSite=Lax or Strict.

Part Not started

The same-origin policy and CORS

An origin is the scheme, host and port of a URL: https://shop.example and https://api.shop.example are different origins, and so are http:// and https:// versions of the same host.

The browser’s same-origin policy says: a page may send requests to other origins, but it may not read the responses, unless the other server allows it. Without that rule, any website you visit could call your bank’s API with your cookies and read your balance.

CORSCORSCross-Origin Resource Sharing: headers with which a server allows pages from other origins to read its responses.Open in glossary → (Cross-Origin Resource Sharing) is how a server allows it. When https://shop.example calls https://api.shop.example, the browser adds an Origin header, and the API answers with a permission:

GET /products HTTP/1.1
Host: api.shop.example
Origin: https://shop.example

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://shop.example

If the header is missing or names another origin, the browser hides the response from the page and fetch fails with a TypeError. The console says “blocked by CORS policy”.

For requests that could change things in ways old HTML forms never could, like Content-Type: application/json, custom headers such as Authorization, or methods like PUT and DELETE, the browser first asks permission with a preflight: an OPTIONS request describing what it wants to send. Only if the server’s answer allows it does the real request go out.

OPTIONS /orders HTTP/1.1
Origin: https://shop.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type, authorization

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://shop.example
Access-Control-Allow-Methods: GET, POST, DELETE
Access-Control-Allow-Headers: content-type, authorization
Access-Control-Max-Age: 600

Two things surprise everyone: CORS errors are fixed on the server, not in the front-end code; and CORS exists only in browsers. curl, Postman, backend services and iOS or Android apps don’t send preflights and ignore these headers completely.

  • Simple requests (GET, HEAD, POST with text/plain, application/x-www-form-urlencoded or multipart/form-data and only safelisted headers) skip the preflight and are sent; CORS only decides whether the page sees the response. The server must not rely on CORS to stop state changes.
  • Credentials: cookies on cross-origin fetch need credentials: 'include' on the client and, on the server, Access-Control-Allow-Credentials: true with an exact Access-Control-Allow-Origin (not *); * is also invalid for Allow-Headers and Allow-Methods in credentialed requests. SameSite still applies on top.
  • Caching: when the allowed origin varies per request, send Vary: Origin, or a CDN serves one origin’s CORS header to another. Access-Control-Max-Age caches preflights (browsers cap it: Chrome at 2 hours).
  • Reading headers: only safelisted response headers are visible to JavaScript unless listed in Access-Control-Expose-Headers (for example ETag, X-Request-ID).
  • mode: 'no-cors' doesn’t bypass anything: it returns an opaque response with status 0 and no readable body.
  • Avoid CORS entirely by serving the front end and API from one origin (shop.example/api through a reverse proxy or CDN routing), which also removes preflight latency.
  • Local Network Access: Chrome now asks the user for permission before a public site may call private IPs or localhost (routers, printers, local dev servers); it replaced the earlier Private Network Access preflights.

Predict the output

A page on http://localhost:8097 runs the code below against http://127.0.0.1:8097, a different origin that sends no CORS headers. The fetch fails with 'TypeError: Failed to fetch'. Did the server receive and process the POST?

await fetch('http://127.0.0.1:8097/simple', {
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  body: 'a=1',
});
// Ktor
install(CORS) {
    allowHost("shop.example", schemes = listOf("https"))
    allowHost("admin.shop.example", schemes = listOf("https"))
    allowHeader(HttpHeaders.ContentType)
    allowHeader(HttpHeaders.Authorization)
    allowMethod(HttpMethod.Put)
    allowMethod(HttpMethod.Delete)
    allowCredentials = true
    maxAgeInSeconds = 600
}
// Spring Boot
@Configuration
class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
            .allowedOrigins("https://shop.example", "https://admin.shop.example")
            .allowedMethods("GET", "POST", "PUT", "DELETE")
            .allowedHeaders("Content-Type", "Authorization")
            .allowCredentials(true)
            .maxAge(600);
    }
}
// Express: an explicit allowlist, credentials, cached preflights
const allowed = new Set(['https://shop.example', 'https://admin.shop.example']);

app.use((req, res, next) => {
  const origin = req.get('Origin');
  if (origin && allowed.has(origin)) {
    res.set({
      'Access-Control-Allow-Origin': origin,
      'Access-Control-Allow-Credentials': 'true',
      'Access-Control-Expose-Headers': 'ETag, X-Request-ID',
    });
  }
  res.vary('Origin');
  if (req.method === 'OPTIONS') {
    res.set({
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
      'Access-Control-Max-Age': '600',
    });
    return res.status(204).end();
  }
  next();
});

Practice: why is it blocked?

Exercisemedium

Read the CORS error

The front end at https://shop.example calls https://api.shop.example. Explain each console message and the server-side fix.

  1. No 'Access-Control-Allow-Origin' header is present on the requested resource.
  2. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present. The GET requests work; this is a POST with JSON.
  3. The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
  4. Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
  5. It works for the first user from https://shop.example, but https://admin.shop.example gets a header naming https://shop.example. The API is behind a CDN.
›

Each message names the header that’s missing or wrong. For the last one, think about who stored the response.

SolutionTry it yourself first
  1. The API sends no CORS header. Add Access-Control-Allow-Origin: https://shop.example (from an allowlist).
  2. The preflight isn’t handled. JSON triggers an OPTIONS request first, and the server (or a framework route) doesn’t answer it with CORS headers, often returning 404 or 401 because the auth middleware runs before CORS. Answer OPTIONS with the allow headers, before authentication.
  3. Credentials with a wildcard. With cookies, the server must echo the exact allowed origin and send Access-Control-Allow-Credentials: true.
  4. The preflight answer doesn’t list Authorization. Add it to Access-Control-Allow-Headers.
  5. The CDN cached one origin’s answer and serves it to everyone. Send Vary: Origin, so the cache keeps one copy per origin.
Deep diveCORS misconfigurations that leak dataInterview favorite

“Review our CORS setup.” The dangerous cases all combine credentials with an origin check that’s too generous, because then any site the user visits can read their data through their cookies.

  • Reflecting any origin: Access-Control-Allow-Origin: <whatever Origin says> plus Allow-Credentials: true. Common when someone fixes error 3 above by copying the request’s Origin. Every website can now read /api/me as the visitor.
  • Weak matching: origin.endsWith('shop.example') accepts evilshop.example; a regex ^https://.*shop\.example without an end anchor accepts https://shop.example.evil.example; startsWith has the mirror problem. Compare against an exact allowlist.
  • Allowing null: sandboxed iframes, file:// pages and some redirects send Origin: null, and attackers can produce it on purpose. Never allow it with credentials.
  • Trusting every subdomain with credentials, then having an XSS on one forgotten subdomain or a takeover of a dangling one.
  • Missing Vary: Origin with dynamic origins: cache confusion, either broken CORS or, with a misconfigured cache key, a permissive header served widely.
  • Treating CORS as access control: CORS stops other sites from reading responses in a browser; it doesn’t authenticate anyone. Endpoints still need authentication and authorization, and state-changing simple requests still arrive (see CSRF in the next part).

A good review answer: an exact allowlist per environment, credentials only where cookies are actually used (bearer tokens in Authorization don’t need Allow-Credentials), Vary: Origin, preflight answered before auth middleware, and ideally one origin for the front end and API so most of this disappears.

  • SOP: other origins may receive requests, not be read. CORS: Access-Control-Allow-Origin (+ Allow-Credentials, Expose-Headers).
  • Simple requests are sent anyway (state changes happen); JSON, Authorization, PUT/DELETE trigger an OPTIONS preflight (Allow-Methods, Allow-Headers, Max-Age).
  • Credentials: exact origin, never *; Vary: Origin; answer preflights before auth.
  • Leaks: reflected origins, suffix/regex matching, null, all subdomains. Only browsers enforce CORS; same-origin API routing avoids it.
Access-Control-Allow-Origin: https://shop.example
Access-Control-Allow-Credentials: true
Vary: Origin

Check this part

  1. Where is a CORS error fixed?

  2. Does an Android app calling the API with OkHttp need CORS headers?

  3. A cross-origin form-encoded POST fails with a CORS error. Did the server process it?

  4. Which origin check is safe with credentials?

The same-origin policy stops a page from reading responses from other origins. CORS lets a server allow it with Access-Control-Allow-Origin. Simple requests are sent anyway and only the response is hidden; other requests (JSON, custom headers, PUT, DELETE) are preceded by an OPTIONS preflight. Credentials need an exact origin, never *. CORS protects users in browsers, not servers: curl and mobile apps ignore it.

Part Not started

Sessions, tokens and CSRF

After a successful login, the server has to recognise the user on later requests. There are two main ways:

Where the client keeps the credential matters:

  • Web apps: an HttpOnly cookie is the safest place, because scripts can’t read it. A token in localStorage can be stolen by any injected script.
  • iOS apps: the Keychain. Android apps: storage encrypted with a key from the Android Keystore. Never plain UserDefaults or SharedPreferences. The token is sent as Authorization: Bearer ….

Cookies come with one danger of their own: the browser attaches them automatically, even to requests that another site triggers. That’s CSRF (cross-site request forgery): a page on evil.example submits a hidden form to bank.example/transfer, and the user’s own cookie makes it look legitimate. SameSite=Lax cookies already block cross-site form posts and background requests; add a CSRF token (a random value the page includes in each form, which another site can’t know) or check the Origin header for anything that changes data.

  • Sessions: revocable instantly, small cookie, one lookup per request (cheap in Redis); rotate the ID on login and privilege change; absolute and idle timeouts; list and revoke devices.
  • JWT access tokens: stateless checks and easy verification across services, but no instant revocation (short expiry, or a deny list, which reintroduces state), size on every request, and pitfalls: verify the algorithm (never alg: none, never let the token pick HMAC with a public key), check exp, aud and iss, rotate signing keys via JWKS.
  • Refresh tokens: long-lived, stored securely, rotated on every use with reuse detection (a replayed old refresh token revokes the whole family, since it means theft). On the web, keep them in an HttpOnly cookie scoped to the refresh endpoint, or use a backend-for-frontend that holds tokens server-side.
  • Mobile: OAuth 2.0 authorization code flow with PKCE through the system browser (ASWebAuthenticationSession, Custom Tabs), never an embedded WebView for third-party logins; Keychain with an appropriate accessibility class, Keystore-backed encryption; optional binding to biometrics; certificate pinning only with the caveats from the TLS lesson.
  • CSRF defences: SameSite Lax or Strict, synchronizer or double-submit tokens, Origin/Sec-Fetch-Site checks, no state changes on GET. Bearer tokens in Authorization aren’t sent automatically, so they aren’t vulnerable to CSRF, but they’re exposed to XSS instead.
  • XSS is the bigger threat: an injected script can act as the user in the page whatever the storage; HttpOnly only stops it from taking the credential away. Content Security Policy and output encoding come first.

Predict the output

bank.example uses a session cookie with SameSite=Lax. Its transfer endpoint accepts GET /transfer?to=...&amount=... . The user, logged in, visits evil.example, which contains the link below and tricks them into clicking it. Does the transfer happen?

<!-- on https://evil.example -->
<a href="https://bank.example/transfer?to=attacker&amount=500">You won a prize, click here</a>
// iOS: save the refresh token in the Keychain, only readable after first unlock
func saveRefreshToken(_ token: String) throws {
    let query: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrService as String: "com.shop.auth",
        kSecAttrAccount as String: "refresh-token",
    ]
    SecItemDelete(query as CFDictionary)
    var attributes = query
    attributes[kSecValueData as String] = Data(token.utf8)
    attributes[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
    let status = SecItemAdd(attributes as CFDictionary, nil)
    guard status == errSecSuccess else { throw KeychainError(status) }
}
// Android: encrypt with an AES key that lives in the Android Keystore
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
val key = (keyStore.getKey("auth", null) as SecretKey?) ?: KeyGenerator
    .getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
    .apply {
        init(KeyGenParameterSpec.Builder("auth", KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
            .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
            .build())
    }.generateKey()

val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.ENCRYPT_MODE, key) }
val encrypted = cipher.iv + cipher.doFinal(refreshToken.toByteArray())
dataStore.edit { it[REFRESH_TOKEN] = Base64.encodeToString(encrypted, Base64.NO_WRAP) }
// OkHttp: attach the access token, refresh once on 401
class AuthAuthenticator(private val auth: AuthRepository) : Authenticator {
    override fun authenticate(route: Route?, response: Response): Request? {
        if (response.request.header("Authorization") != null && response.priorResponse != null) return null
        val token = runBlocking { auth.refreshAccessToken() } ?: return null   // logs out on failure
        return response.request.newBuilder().header("Authorization", "Bearer $token").build()
    }
}

Practice: where does the credential go?

Exercisemedium

Storing a login

For each client, say where the login credential should be stored and how it’s sent, and name the main attack you’re protecting against.

  1. A server-rendered web shop (HTML from the server, forms).
  2. A single-page app at https://shop.example calling https://shop.example/api.
  3. An iOS app calling https://api.shop.example.
  4. An Android app calling the same API.
  5. A command-line tool for developers.
›

Is there a browser involved? If yes, can scripts reach the credential, and does the browser send it automatically?

SolutionTry it yourself first
  1. A session ID in a Secure; HttpOnly; SameSite=Lax cookie, stored server-side. Protect against CSRF with SameSite and CSRF tokens in forms.
  2. Also an HttpOnly session cookie (same origin, so no CORS or third-party issues), not a token in localStorage, where any injected script could read it. Protect against XSS (Content Security Policy, escaping) and CSRF (SameSite, Origin checks on writes).
  3. Access and refresh tokens in the Keychain, sent as Authorization: Bearer …. Protect against token theft from backups or a jailbroken device with a ThisDeviceOnly accessibility class, and use short-lived access tokens.
  4. Tokens encrypted with a Keystore key (DataStore or a database holding the ciphertext), sent as Authorization: Bearer …. Same reasoning; never plain SharedPreferences.
  5. A token in the operating system’s credential store (macOS Keychain, Windows Credential Manager, libsecret), or at least a config file readable only by the user, with a scoped, expiring personal access token.
Deep diveSessions or JWTs?Interview favorite

“Should we use JWTs or server sessions?” Interviewers want trade-offs, not a favourite.

Server sessions (random ID in a cookie, state in Redis or the database): instant logout and revocation (“log out all devices”, ban a user, react to a stolen session), tiny cookies, nothing sensitive on the client. Cost: a lookup per request (sub-millisecond in Redis) and a shared store every service must reach. They’re the default for a monolith or a web app with a backend.

Self-contained tokens (JWT or PASETO access tokens): any service can verify them with a public key, no shared store, good for many independent services and third-party APIs. Cost: you can’t revoke one before it expires, so lifetimes must be short (5 to 15 minutes), which brings refresh tokens, and refresh tokens are server-side state again. Tokens grow with claims, travel on every request, and their claims (roles, plan) go stale until the next refresh.

A strong answer:

  • For a web app, server sessions in HttpOnly cookies, or a backend-for-frontend that holds OAuth tokens server-side and gives the browser only a session cookie.
  • For mobile apps and public APIs, short-lived access tokens (JWTs are fine) plus rotating refresh tokens with reuse detection, stored in Keychain or Keystore.
  • Inside the backend, the gateway can exchange a session for a short-lived signed internal token, so services verify without a lookup.
  • Revocation needs: a deny list for emergencies, refresh-token revocation, and short access-token lifetimes; key rotation through JWKS with kid.
  • Pitfalls to name: storing tokens in localStorage, long-lived JWTs without revocation, accepting unsigned or wrongly signed tokens, putting personal data in the payload (it’s encoded, not encrypted).
  • Sessions: random ID in a cookie, state server-side, instant revocation, rotate on login. JWTs: stateless verification, short expiry, refresh tokens rotated with reuse detection.
  • Web: HttpOnly cookies or a backend-for-frontend, not localStorage. Mobile: Keychain / Keystore, Authorization: Bearer, OAuth code flow with PKCE in the system browser.
  • CSRF: cookies are sent automatically. SameSite Lax/Strict, CSRF tokens, Origin/Sec-Fetch-Site checks, never change state on GET. Bearer tokens avoid CSRF but not XSS.
  • JWT checks: algorithm pinned, exp, aud, iss, keys via JWKS; payload isn’t secret.
Authorization: Bearer eyJhbGciOiJFUzI1NiIsImtpZCI6IjIwMjYtMTEifQ...
Cookie: __Host-session=8f2c91d4

Check this part

  1. Where should an iOS app store its refresh token?

  2. Why are cookie-based logins exposed to CSRF?

  3. A replayed refresh token is detected (it was already rotated). What should the server do?

  4. What is the main downside of long-lived JWT access tokens?

After login the server either stores a session and gives the client a random ID (usually in a cookie), or issues a signed token such as a JWT (usually a short-lived access token plus a refresh token). In browsers, HttpOnly cookies keep tokens away from injected scripts but need CSRF protection; on mobile, tokens go in the Keychain or Keystore-backed storage and travel in the Authorization header.

Key takeaways

  • Servers set cookies with Set-Cookie; browsers send them back automatically to matching requests.
  • Session cookies: Secure, HttpOnly, SameSite=Lax. Without SameSite, browsers apply Lax.
  • The same-origin policy hides other origins’ responses; CORS headers from the server allow them. Only browsers enforce it.
  • JSON, custom headers and PUT or DELETE trigger an OPTIONS preflight first.
  • Web logins belong in HttpOnly cookies with CSRF protection; mobile tokens in the Keychain or Keystore.
  • Site (SameSite) vs origin (CORS); subdomains are same-site, so use __Host- cookies and keep untrusted content on another domain.
  • Simple cross-origin requests still execute; credentials need an exact allowlisted origin and Vary: Origin.
  • Sessions for revocability, short JWTs plus rotating refresh tokens for distributed APIs and mobile.
  • CSRF defences rely on safe GETs; XSS defeats every storage choice, so CSP and encoding come first.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.