Where should the JWT be stored? did you find it?

I have used JWT as an authentication token for projects in recent years. I have always had a question: Where should the JWT sent by the server to the browser be stored? Here we only discuss the browser scenario. There are three options in this scenario.


I have used JWT as an authentication token for projects in recent years. I have always had a question: Where should the JWT sent by the server to the browser be stored? Here we only discuss the browser scenario. There are three options in this scenario.

 

Cookies

The server can send the JWT token to the browser through the Cookie, and the browser will automatically bring the JWT token in the Cookie header when requesting the server interface. The server can verify the JWT token in the Cookie header to achieve identity verify. But it is vulnerable to CSRF attacks.

 

The solution is to set the SameSite attribute of Cookie to Strict. Cookies will not be sent when cross-site. In other words, only if the URL of the current web page is consistent with the request target, the cookie will be carried.

 

In addition to being vulnerable to CSRF attacks, cookies are also XSS attacks. Hackers can read the information in Cookie through JS script. To prevent this, you can set the Cookie attribute to HttpOnly.

You can set its lifetime by setting Max-Age.

 

localStorage

localStorage can also store JWT tokens. This method is not susceptible to CSRF. But unlike Cookie, it does not automatically carry the token in the request, it needs to be implemented through code. But this will be attacked by XSS. In addition, if the user does not actively clear the JWT token, it will always be stored in localStorage.

 

sessionStorage

Most of the features of sessionStorage are similar to localStorage, but its life cycle is different from localStorage. It is session-level storage. It will be cleared after closing the page or browser.

 

Summarize

You may notice that all three methods have the same shortcoming-"vulnerability to XSS attacks." Please pay special attention to XSS protection and always follow the best practices of XSS protection.

 

in conclusion

All three forms are prone to XSS attacks. Therefore, if the security requirements are high, special targeted configuration is required. Among the three methods, Cookie provides a bunch of security options, such as SameSite, HttpOnly, etc. Therefore it is best to use cookies.

 

This article is reproduced from the WeChat public account "Ma Nong Pang Brother", you can follow the QR code below. To reprint this article, please contact the official account of the code farmer.