I have been using JWT as authentication token for my projects in the last few years. I’ve always had a question: where exactly should the server-side issued JWT be stored? Only the browser scenario is discussed here, in which there are three options.
The server side can send the JWT token to the browser through a cookie, and the browser will automatically bring the JWT token in the cookie header when requesting the server-side interface, and the server side can verify the JWT token in the cookie header to achieve authentication. However, it is vulnerable to CSRF attacks.
The solution is to set the
SameSite property of the cookie to
Strict. In other words, only if the URL of the current page is the same as the target of the request, the cookie will be carried.
Cookies are not only vulnerable to CSRF attacks but also XSS attacks. Hackers can read the information in cookies through JS scripts. To prevent this, you can set the cookie’s property to
You can set its survival time by setting
localStorage can also store JWT tokens, and this method is less susceptible to CSRF. However, unlike cookies, it doesn’t automatically carry the token in the request and needs to be implemented by code. However, this will be subject to XSS attacks. In addition, if the user does not actively clear the JWT token, it will always be stored in localStorage.
Most of the features of sessionStorage are similar to localStorage, but its lifecycle differs from localStorage in that it is session-level storage. It will be cleared after closing the page or browser .
You may notice that all 3 methods have the same drawback - “vulnerable to XSS attacks”. Please be aware of XSS protection and always follow the best practices for XSS protection.
All three forms are susceptible to XSS attacks, so if security is critical, configure them in a particularly targeted way. Among the three, cookies provide a bunch of security options, such as