Hasty Briefsbeta

Bilingual

What's the best way to do authentication in modern applications

4 hours ago
  • #frontend development
  • #web security
  • #authentication
  • JWTs are commonly used for authentication but storing them in localStorage makes them vulnerable to XSS attacks, as any JavaScript on the page can read localStorage.
  • Using HTTP-only cookies with flags like Secure and SameSite=Lax prevents JavaScript from reading tokens, reducing the risk of token exfiltration during XSS attacks.
  • CSRF attacks are a risk with cookies, but can be mitigated using CSRF tokens, SameSite attributes, and checking request headers like Origin or Sec-Fetch-Site.
  • Stateless JWTs have revocation issues; server-side sessions with opaque session IDs in HTTP-only cookies allow immediate session invalidation and are more secure for single applications.
  • For OAuth or third-party tokens, use a Backend for Frontend (BFF) pattern where tokens are stored server-side, and the browser only holds an HTTP-only session cookie, preventing token exposure to JavaScript.
  • Refresh token rotation and reuse detection enhance security by invalidating stolen refresh tokens and forcing re-authentication.
  • Device Bound Session Credentials (DBSC) bind sessions to hardware, preventing stolen cookies from being used long-term, though adoption is currently limited.
  • For React applications, centralize token handling in an API wrapper to manage token refresh and prevent concurrent refresh requests from causing logout.