Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Admin Auth — Cookie-Backed Refresh Tokens
Status: Implemented in 5.5
Target: Spree 5.5
Depends on: 6.0-admin-spa.md
Related: 6.0-platform-auth.md (broader auth direction, lands in 6.0)
Author: Damian Legawiec
Last updated: 2026-05-20
Summary
The Admin SPA currently stores both the JWT access token and the long-lived refresh token in localStorage, where any JavaScript on the page can read them. This plan moves the refresh token into an HttpOnly signed cookie scoped to /api/v3/admin/auth, keeps the short-lived access token in JS memory only, and introduces a real server-side logout that destroys the Spree::RefreshToken row. Server-to-server integrations using secret API keys are unaffected.
The design follows Saleor's storefront Auth SDK pattern — access token in memory, refresh token in httpOnly cookie — adapted to our existing Spree::RefreshToken rotation infrastructure. CSRF protection is delivered by the SameSite + CORS allowlist combination already in place; no separate CSRF token is issued.
Key Decisions (do not deviate without discussion)
- Refresh token delivery:
Set-Cookieon/auth/loginand/auth/refresh. Never returned in the JSON response body. - Cookie attributes:
HttpOnly; SameSite=Lax; Path=/api/v3/admin/authon plain-http requests,HttpOnly; Secure; SameSite=None; Path=/api/v3/admin/authon https requests (keyed offrequest.ssl?, not the Rails env — Rails silently drops Secure cookies on non-SSL requests, which broke production images served over http://localhost). Cookie is signed via Railscookies.signedfor tamper-evidence. - Cookie name:
spree_admin_refresh_token. - Access token storage: React state only. No
localStorage, nosessionStorage. - CSRF protection: Provided by the combination of (a)
SameSite=Lax/SameSite=Nonecookie attributes and (b)Spree::AllowedOriginenforced viaRack::Corswithcredentials: true. No separate CSRF token is issued or verified. Reasoning: a cross-origin attacker cannot pass the CORS preflight (Origin not on the allowlist), andSameSiteblocks cross-site form/POST autosubmits independently. A double-submit token would only add value if the AllowedOrigin allowlist were misconfigured (*) or if XSS happened on a different allowlisted origin — both scenarios where deeper problems outweigh the CSRF mitigation, and where an in-memory CSRF token has the same XSS exposure as the access token anyway. - Cookie scope:
Path=/api/v3/admin/authso the refresh cookie is only sent to login/refresh/logout, never on/products,/orders, etc. - Logout: new
POST /api/v3/admin/auth/logoutendpoint clears the cookie viaSet-CookiewithMax-Age=0and destroys theSpree::RefreshTokenrow server-side (matching the hard-delete pattern inRefreshToken#rotate!). Idempotent — succeeds even when no session exists. - No special-casing for secret-key clients: secret-key flows never hit
/auth/login(they use the key directly). The backend sets cookies unconditionally on login responses; non-browser clients ignoreSet-Cookie. - Local development: uses Vite proxy (
/api/*→:3000) so the SPA is same-origin with the API. Cookie attributes are scheme-conditional:SameSite=LaxwithoutSecureover http,SameSite=None; Secureover https. - Bootstrap: SPA calls
/auth/refreshon cold load before rendering authenticated routes. Success → in-memory access token, render. Failure → render/login. - No backwards compatibility window:
@spree/admin-sdkis unreleased (Developer Preview,nextdist-tag) so we don't need a transition period. The 5.5 release ships the cookie-only contract directly: refresh token only via cookie, norefresh_tokenfield in response bodies, noparams[:refresh_token]body fallback. - Admin JWT TTL is 5 minutes (separate from storefront). A new
Spree::Api::Config[:admin_jwt_expiration](default 300s) is consumed only bySpree::Api::V3::Admin::AuthController#jwt_expiration. The generalSpree::Api::Config[:jwt_expiration](default 3600s) continues to govern Store API tokens — customer JWTs have lower blast radius and don't justify the refresh chatter. SPA's background refresh schedule is4m30s(30s before expiry); 401-driven refresh handles the rest. - CORS: no changes.
Spree::AllowedOrigin+credentials: trueon/api/v3/admin/*already supports browser cookies.
Design Details
Cookie contract
| Cookie | Attributes (https) | Attributes (http) | Set on | Cleared on |
|---|---|---|---|---|
spree_admin_refresh_token |
HttpOnly; Secure; SameSite=None; Path=/api/v3/admin/auth (signed) |
HttpOnly; SameSite=Lax; Path=/api/v3/admin/auth (signed) |
/auth/login, /auth/refresh (rotation) |
/auth/logout, refresh failure |
Cookie expiry: Max-Age matches the refresh token's natural lifetime (Spree::RefreshToken config, default 30 days). On refresh, the cookie is re-issued with the new value and a fresh Max-Age (sliding window).
Why no CSRF token?
Classic CSRF assumes the attacker can trigger an authenticated request from a different origin and only needs the cookie to be auto-attached. Three independent defenses already block this for our setup:
SameSite=Lax(http) blocks cross-site POSTs entirely. The cookie won't be attached.SameSite=None; Secure(https) is the only mode that allows cross-site cookie attachment, and it is constrained by:- CORS preflight +
Spree::AllowedOrigin— for any cross-origin authenticated POST, the browser sends anOPTIONSpreflight.Rack::CorsechoesAccess-Control-Allow-Originonly for origins onSpree::AllowedOrigin. An attacker's origin (evil.com) is not on the allowlist, the preflight fails, and the browser blocks the actual POST. The cookie is never sent.
A double-submit CSRF token would only add value in two narrow scenarios:
- A merchant misconfigures
AllowedOrigin(e.g. adds*). The CSRF token would still hold, but this is "defense against the merchant breaking their own allowlist." - XSS on a different allowlisted origin (e.g. their storefront). An in-memory CSRF token would technically not be readable from the storefront's JS, but at that point the attacker controls a trusted page and can do significantly more damage than CSRF would unlock.
Storing the CSRF token in localStorage or JS memory gives it the same XSS exposure profile as the access token — when XSS lands on the admin SPA itself, both leak together. So a CSRF token wouldn't add real defense over what we already have, while adding real complexity (cookie/header plumbing, edge cases around rotation, document.cookie reads). Skipped deliberately.
Backend — Spree::Api::V3::Admin::AuthController
POST /api/v3/admin/auth/login
Request body unchanged: { email, password, provider? }.
Response body:
{
"token": "eyJ...",
"user": { ... }
}
Set-Cookie header:
spree_admin_refresh_token=<signed_value>; HttpOnly; Secure; SameSite=None; Path=/api/v3/admin/auth; Max-Age=2592000(https)spree_admin_refresh_token=<signed_value>; HttpOnly; SameSite=Lax; Path=/api/v3/admin/auth; Max-Age=2592000(http)
POST /api/v3/admin/auth/refresh
Request: empty body. Reads refresh token from cookies.signed[:spree_admin_refresh_token].
If cookie missing → 401 invalid_refresh_token.
If cookie present but Spree::RefreshToken.active.find_by(token: ...) returns nil → clear the cookie and return 401 invalid_refresh_token (the cookie pointed to a revoked or expired row).
On success → rotate the row (RefreshToken#rotate!), set the new cookie, return { token, user }.
POST /api/v3/admin/auth/logout
Request: empty body. No CSRF check; the only credential is the cookie. (CSRF defense applies via SameSite + CORS as described above.)
Behavior:
- Look up
Spree::RefreshToken.active.find_by(token: cookie_value). - If found,
destroy!it. Set-CookiewithMax-Age=0to clear the cookie.- Return
204 No Contentwhether or not the row was found (idempotent).
sdk-core — credentials seam
RequestConfig gains an optional field:
export interface RequestConfig {
baseUrl: string
fetchFn: typeof fetch
retryConfig: Required<RetryConfig> | false
credentials?: RequestCredentials // 'omit' | 'same-origin' | 'include'
}
Threaded into the fetch() call:
const response = await config.fetchFn(url.toString(), {
method,
headers: requestHeaders,
body: body ? JSON.stringify(body) : undefined,
credentials: config.credentials,
})
No behavior change for the Store SDK (omits the field). When baseUrl is empty (browser → Vite proxy), the SDK resolves the relative path against window.location.origin so new URL doesn't throw.
@spree/admin-sdk — cookie auth + logout
AdminClientConfig gains an optional field:
/** Send cookies on cross-origin requests. Defaults to 'include' for cookie-based auth. */
credentials?: RequestCredentials
Default is 'include' — admin clients are always browser-driven or proxied; secret-key flows ignore cookies harmlessly.
AdminAuthResource:
auth = {
login(credentials): Promise<AuthTokens> // POST /auth/login
refresh(): Promise<AuthTokens> // POST /auth/refresh, no body
logout(): Promise<void> // POST /auth/logout
}
AuthTokens is { token, user } — no refresh_token.
The constructor's secretKey || jwtToken guard is relaxed so a cookie-auth SPA can boot empty and bootstrap via auth.refresh().
Admin SPA — auth-provider.tsx
Storage:
- Removed:
TOKEN_KEY,REFRESH_TOKEN_KEY,USER_KEYlocalStorage entries. - Removed:
localStorage.getItem(TOKEN_KEY)frompackages/dashboard/src/client.ts(initial token now empty). - Kept:
useStatefor token, user, isLoading. - New:
isInitializingstate — true until cold-load/auth/refreshsettles.
Bootstrap flow on mount:
useEffect(() => {
refreshAccessToken()
.then((success) => { if (success) scheduleRefresh() })
.finally(() => setIsInitializing(false))
}, [])
Route guards (_authenticated.tsx, login.tsx, _authenticated/index.tsx) wait for isInitializing === false before deciding to redirect. main.tsx calls router.invalidate() when auth state changes so the guards re-run with fresh context.
Login flow: unchanged shape, no localStorage writes.
Logout flow: calls adminClient.auth.logout(), then clears React state + refresh timer. Network failure on logout still clears local state (server-side row will expire naturally).
401 handler: unchanged — calls refresh, retries. The handler doesn't need to know that refresh now reads from cookies; that's encapsulated in the SDK.
Local dev — Vite proxy
packages/dashboard/vite.config.ts proxies /api/* to http://localhost:3000 so the SPA is same-origin with the Rails API. Same-origin keeps SameSite=Lax cookies working without HTTPS. Production builds (with VITE_SPREE_API_URL set to the absolute API origin) hit cross-origin and use SameSite=None; Secure.
packages/dashboard/src/client.ts:
const baseUrl = import.meta.env.VITE_SPREE_API_URL || ''
export const adminClient = createAdminClient({
baseUrl,
// No initial token — auth-provider bootstraps via /auth/refresh on mount.
})
Migration Path
Shipping as a single coordinated PR for Spree 5.5. Backend, SDK and SPA all change at once because @spree/admin-sdk is unreleased (Developer Preview / next dist-tag) and the SPA is its only consumer — there are no external clients to coordinate with.
The work landed in two commits on the PR branch:
Commit 1 — Cookie-Backed Refresh Tokens
- New concern
Spree::Api::V3::Admin::AuthCookies(cookie helper, env-conditional attributes). AuthController#createsets cookie; removerefresh_tokenfrom response body.AuthController#refreshreads refresh token from cookie only.AuthController#logoutnew action — destroys row + clears cookie.- Routes: add
POST /api/v3/admin/auth/logout. sdk-core: addcredentialstoRequestConfig, thread to fetch. Resolve relative URLs againstwindow.location.originwhenbaseUrlis empty.admin-sdk: defaultcredentials: 'include', droprefresh_tokenfromAuthTokens,auth.refresh()no body,auth.logout()new action, relax constructor guard.- Vite proxy on
packages/dashboard/vite.config.tsso the SPA is same-origin with the API in dev. auth-provider.tsxrewrite — in-memory token + bootstrap via/auth/refresh, nolocalStorage.isInitializingplumbed through router context; guards in_authenticated.tsx,_authenticated/index.tsx,login.tsx.main.tsx:router.invalidate()on auth state change.- RSpec: cookie set/clear, refresh rotation, logout destroys row, missing-cookie 401, missing-row 401 + cookie-clear.
- Vitest: credentials passthrough, refresh sends no body, logout reaches the endpoint.
- Changeset for
@spree/admin-sdk.
No model or migration changes — reuses existing RefreshToken infrastructure.
Commit 2 — Reduce Admin JWT TTL to 5 minutes
- New
Spree::Api::Config[:admin_jwt_expiration]preference (300s default). Admin::AuthControlleroverridesjwt_expirationto read the admin-specific config.- SPA refresh interval shortened to
4m30sto match. - Storefront JWT TTL untouched (still 3600s) — customer tokens have lower blast radius.
Follow-up — OpenAPI + docs
- Regenerate admin OpenAPI spec.
- Update
packages/dashboard/README.mdauth section. - Update developer docs in
docs/developer/if they describe the old shape.
Constraints on Current Work
Until this lands:
- Don't add features that depend on the refresh token being readable in JS. No "show me my session expiry" UI built off the localStorage value, no analytics on token rotation timing from the client. Server-driven only.
- Don't write new admin code that reads
localStorage.getItem('spree_admin_token')outside the auth provider. The token belongs in React state and the SDK, not scattered. - New admin endpoints that mutate state should not reuse the
Path=/api/v3/admin/authscope — that path is reserved for auth flows specifically so the refresh cookie's blast radius stays minimal. - Don't broaden
Spree::AllowedOriginto*. The CORS allowlist is now load-bearing for CSRF defense, not just access control.
Open Questions
- Multi-tab coordination: if a user logs out in tab A, tab B still has a valid in-memory access token until its next refresh attempt (which will 401, trigger a refresh that fails because the row was destroyed, and bounce to login). Acceptable, or should we add a
BroadcastChannelto coordinate? Recommend: defer, ship without. - HMR remounts log the user out in dev: AuthProvider remount → in-memory token resets → bootstrap fires
/auth/refreshwhich should re-hydrate. If the bootstrap is slow or the user is on a route that fires data fetches before bootstrap settles, they may see brief 401s before re-hydration completes. Production never HMRs, so this is dev-only friction. - Mobile app / non-browser admin clients: if anyone embeds the admin in a webview without cookie support, the cookie path breaks. Currently no known case. Document the SPA's browser-only assumption.
- Refresh token rotation telemetry: today we log refresh rotations to
Spree::RefreshTokenrows. Cookie-based flow keeps this. Worth surfacing as an admin "active sessions" UI in a follow-up? - Instant access-token revocation: stateless JWTs are valid until their
expclaim regardless of server-side state, so logout doesn't immediately kill an in-flight access token (worst case ~5 min until natural expiry). Three follow-up options exist (5-min TTL — already done; per-usertokens_invalid_beforestamp; full JTI denylist with cache-backed lookup). Do nothing further unless an active-sessions UI or compliance requirement demands it. - Active sessions UI:
Spree::RefreshTokenalready recordsip_address+user_agentper rotation. A "see and revoke active sessions" admin screen would unlock JTI revocation as a natural follow-up. Defer.
References
docs/plans/6.0-platform-auth.md— broader auth directiondocs/plans/6.0-admin-spa.md— admin SPA architecturespree/api/app/controllers/spree/api/v3/admin/auth_controller.rb— current implementationspree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb— JWT layerpackages/dashboard/src/providers/auth-provider.tsx— SPA auth providerpackages/sdk-core/src/request.ts— shared HTTP layer- Saleor Auth SDK — reference design (refresh in cookie, access in memory)
- OWASP — JWT for Java Cheat Sheet — storage guidance
- MDN —
SameSitecookies — cross-site behavior - Rack::Cors —
credentials: truesemantics