Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon how can I securely store JWT tokens in local storage
    JWT token storage secure JWT storage Laravel JWT Vue.js JWT httpOnly cookies token security JWT best practices Laravel Vue SPA


how can I securely store JWT tokens in local storage


To securely store JWT tokens in local storage, you should avoid using local storage directly and instead use cookies with the `httpOnly` flag. Here are the steps to follow:

1. Use HTTPS:
- Ensure that all communication between the client and server is encrypted using HTTPS. This prevents eavesdropping and tampering with the JWT tokens.

2. Use Cookies with `httpOnly` Flag:
- Store the JWT token in a cookie with the `httpOnly` flag set. This flag prevents JavaScript from accessing the cookie, making it immune to cross-site scripting (XSS) attacks.

php
   // In Laravel
   $token = JWTAuth::attempt($credentials);
   if (!$token) {
       return response()->json(['error' => 'Invalid credentials'], 401);
   }
   return response()->json(['token' => $token]);
   

javascript
   // In Vue.js
   this.$axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
   

3. Set Cookie with `httpOnly` Flag:
- Set the cookie with the `httpOnly` flag to prevent JavaScript from accessing it.

php
   // In Laravel
   return response()->cookie('token', $token, 3600, '/', 'example.com', false, false, 'Secure; HttpOnly');
   

4. Handle Token Revocation:
- Implement a mechanism to revoke JWT tokens when necessary. This can be done by storing the tokens in a database and periodically purging expired tokens.

5. Monitor and Audit JWT Token Usage:
- Monitor and audit JWT token usage to detect potential security issues and unauthorized access.

By following these best practices and implementing the necessary security measures, you can ensure the integrity and security of your JWT tokens in a Laravel-Vue SPA.

Citations:
[1] https://tkacz.pro/how-to-securely-store-jwt-tokens/
[2] https://www.linkedin.com/advice/0/what-best-practices-storing-sending-jwt-tokens
[3] https://codeburst.io/localstorage-vs-cookies-all-you-need-to-know-about-storing-jwt-tokens-securely-in-the-front-end-70dc0a9b3ad3
[4] https://blog.logrocket.com/jwt-authentication-best-practices/
[5] https://www.cyberchief.ai/2023/05/secure-jwt-token-storage.html