Development & Deployment

Handle JWT authentication with Symfony and React

Access/refresh tokens, client interceptors and best practices.

O
Online Toolset TeamEditorial Team
8 min read

Using Symfony + React with JWT enables stateless authentication suited for SPAs and mobile apps, with a secure access/refresh lifecycle.

Key takeaways (TL;DR) Short-lived access token in memory + refresh token as httpOnly cookie with SameSite/Secure. Axios/Fetch interceptors add Bearer and retry the request after 401 if refresh succeeds. On Symfony: LexikJWTAuthenticationBundle, short expiration, refresh rotation/blacklist, rate limits.

JWT basics

  • Structure: header.payload.signature (Base64URL). Standard:RFC 7519
  • Do not store secrets in the payload. Claims are readable by clients.
  • Signature HS256/RS256. Prefer RS256 in production (asymmetric keys).

Symfony (server)

  • Recommended bundle:LexikJWTAuthenticationBundle(generatesprivate.pem/public.pem).
  • Typical endpoints:POST /login_check(issues access+refresh),POST /token/refresh.
  • security.yaml: public vs protected firewalls,jwtauthenticator,access_control.
  • Optional: API Platform to expose resources and protect operations viasecurityexpressions.

React (client)

  • Keep the access token in memory (state), avoidlocalStorageif possible.
  • Store the refresh token in httpOnly cookie + SameSite=Lax/Strict, Secure over HTTPS.
  • Axios/Fetch interceptors: attachAuthorization: Bearer; on 401 attempt one refresh.
  • Requests management: React Query or RTK Query for retries, cache invalidation, and states.

Refresh flow

  1. Request with access token.
  2. If 401 due to expiration, call/token/refresh(refresh cookie goes automatically).
  3. If OK → update access token in memory and retry the original request.
  4. If KO → force logout and redirect to login.

Best practices

  • Access tokens 5–15 mins; refresh 7–30 days with rotation and server-side revocation list.
  • Minimal claims; no sensitive data; setaud,iss,exp.
  • CSRF: if endpoints use cookies, protect with CSRF token and proper SameSite.
  • Rate‑limit/login_checkand/token/refresh; log attempts.

Tools mentioned

  • LexikJWTAuthenticationBundle
  • API Platform
  • Axios, React Query / Redux Toolkit Query
  • Symfony Security
JWTSymfonyReactSecurity

About the author

O
Online Toolset TeamEditorial Team

The Online Toolset editorial team produces practical guides on web development, image optimization, productivity, and digital tools.

Web DevelopmentImage OptimizationDevOpsUI/UXProductivity