BBackend CourseLeroy Labs
0/0
Search the course

Cookies, CORS & CSRF, the browser security trio

HttpOnly/Secure/SameSite/Domain cookie attributes, what CORS really protects (and doesn't), preflight requests, CSRF attacks, and why "CSRF disabled + JWT in a cookie" is a trap.

● advancedSpring-Boot-StoreHostel-Web-AppReport-Manager-2IR3D (Kontentt)SperoTek (in dev)

Cookies

ResponseCookie.from("refreshToken", raw)
    .httpOnly(true)        // JS can't read it, so XSS can't steal it
    .secure(true)          // HTTPS only
    .sameSite("Strict")    // see below
    .path("/api/auth")     // only sent to the auth endpoints
    .domain(".leroylabs.dev")  // shared across subdomains (omit for host-only)
    .maxAge(Duration.ofDays(7))
    .build();

SameSite

Value Sent on cross-site requests? Notes
Strict Never Safest. Clicking a link from email to your site arrives “logged out” for that cookie
Lax (browser default) Only top-level GET navigations Blocks cross-site POST, fetch and iframes
None Always (requires Secure) Needed when the frontend and API are on different sites

“Site” means registrable domain plus scheme. app.leroylabs.dev and api.leroylabs.dev are the same site, while myapp.onrender.com and api.leroylabs.dev are cross-site.

CORS

The Same-Origin Policy stops JS on evil.com from reading responses from api.yours.com. CORS is how your server relaxes that for trusted origins.

OPTIONS /api/bookings            <- preflight for non-simple requests (JSON, Authorization header)
Origin: https://hostel.app
Access-Control-Request-Method: POST

HTTP/1.1 204
Access-Control-Allow-Origin: https://hostel.app
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 3600     <- browser caches this preflight for 1h

What CORS does not do: it doesn’t stop requests from being sent. It only stops the attacker’s JS from reading the response. curl, Postman and servers ignore CORS entirely. CORS is not authentication.

With credentials you cannot use Allow-Origin: *. You must echo specific origins.

CSRF

Cross-Site Request Forgery: the user is logged in to bank.com through a cookie, visits evil.com, and that page auto-submits a form to bank.com/transfer. The browser attaches the cookie automatically, and the transfer runs. The attacker never needs to read the response.

  • If auth is only an Authorization: Bearer header (set by your JS), CSRF isn’t possible, because browsers don’t add that header automatically.
  • If auth relies on a cookie, you need CSRF defences:
    1. SameSite=Strict or Lax (a strong baseline).
    2. A CSRF token (synchronizer or double-submit cookie).
    3. A custom header requirement (cross-site forms can’t set headers without CORS approval), plus Origin/Referer checking.

In your projects

SperoTek (in dev)identity/web/CookieCsrfGuard.java · RefreshCookie · SecurityConfig

This is the textbook approach. Access tokens travel as Bearer headers, so Spring CSRF is disabled for them. The cookie-based endpoints (refresh, logout) are protected by CookieCsrfGuard, which requires a custom header plus an allowed Origin, and otherwise throws CSRF_REJECTED. The refresh cookie is SameSite=Strict. CORS allows origins from FrontendProperties, with credentials, and exposes X-Correlation-Id and Retry-After.

Report-Manager-2shared/config/SecurityConfig.java

⚠️ .csrf(AbstractHttpConfigurer::disable) while the JWT is read from a cookie first. The only protection left is the browser’s SameSite=Lax default. That stops cross-site POSTs in modern browsers, but older browsers, same-site subdomain attacks and any state-changing GET remain exposed. Also, setMaxAge(Duration.ofDays(3600L)) is about 10 years, not the 1 hour its comment claims (browsers cap it at around 2 hours anyway).

Fix: add an Origin check or a custom-header requirement for cookie-authenticated mutations, or enable Spring’s CookieCsrfTokenRepository.

Hostel-Web-AppSecurityConfig.corsConfigurationSource · AuthService.setAuthCookie

CORS uses setAllowedOriginPatterns(List.of(frontendBaseUrl, "http://localhost:5173", ...)) with credentials and setMaxAge(3600L). The refresh cookie’s secure, sameSite and domain are configurable per environment, because local dev on http://localhost can’t use Secure + SameSite=None.

Spring-Boot-StoreSecurityConfig

No CORS config. That’s fine for a backend-only API called by servers or Postman, but a browser frontend on another origin would be blocked.

Decision table

Auth transport CSRF needed? XSS exposure
Bearer header, token in JS memory No Token readable by XSS while the page is open
Bearer header, token in localStorage No Token stealable by XSS permanently
HttpOnly cookie Yes Not stealable, but XSS can still use it from the page
SperoTek hybrid (access in memory, refresh in a Strict HttpOnly cookie + custom header) Guarded Best balance

Check yourself

1. Does CORS stop a malicious site from sending a POST to your API?
2. Auth purely via Authorization: Bearer header set by JS. CSRF risk?
3. app.leroylabs.dev → api.leroylabs.dev is…