In order to securely retrieve and store a JWT in the browser, follow these steps:
1. Receive JWT Securely
- When the user logs in, retrieve the JWT via a secure HTTPS API request.
- Use HTTP-only cookies to store the JWT securely. HTTP-only cookies are not accessible from JavaScript, which helps prevent exposure to XSS attacks.
2. Storage Options
- HTTP-only, Secure Cookies (Preferred): Storing the JWT in an HTTP-only cookie makes it inaccessible to JavaScript, which is ideal for security. This is particularly useful for sensitive applications where security is a priority.
- In-memory storage: If using HTTP-only cookies isn’t feasible (e.g., for certain SPAs), store the JWT in memory (a variable within the app’s code) instead of localStorage or sessionStorage to prevent exposure in the case of XSS attacks.
3. Avoid LocalStorage and SessionStorage
- Avoid using localStorage or sessionStorage for JWTs, as they are vulnerable to JavaScript access, especially in XSS attacks. These storages are accessible by JavaScript on the same domain, making them less secure.
4. Token Renewal and Expiration
- Implement token expiration and a refresh token mechanism to ensure the JWT has a short life. Place the refresh token in an HTTP-only cookie to avoid re-authentication without requiring the user to log in again.
- Set up a refresh flow to obtain a new JWT as needed and keep sessions active securely.
5. Secure Communication
- Always communicate over HTTPS to prevent exposure to attacks like man-in-the-middle (MITM) attacks.
- Use CORS policies on the server to restrict access from unauthorized origins, limiting where JWTs can be requested.