Browser localStorage (or session storage) is not secure. Any stored data may be vulnerable to scripts between sites. If an attacker steals a token, he can access and request your API.
If the application has a backend server, the tokens must be manipulated on the server side using the Web application login flow(
for example: in a backend service done at Nodejs, token validation is done through a middleware that protects a route if the token is invalid ).
Alternative: cookies. You can also use cookies to store JWT. The exact way to set a cookie depends on the language you are using.
A little more about Cookies
There are different options to control the lifespan of a cookie:
Cookies can be destroyed after the browser is closed (session cookies).
Implement a server-side check (usually done by you through the Web language structure in use) and you can implement window expiration or expiration (browser closed).
Cookies can be persistent (not destroyed after the browser is closed) with an expiration date.
Cookies can be read by the server-side code and Javascript or only by the server-side if the flag httpOnly
is defined.
You can set the flag secure = true
so that cookies can only be set on an encrypted connection.
ATTENTION
Disadvantages of cookies:
The maximum size of a cookie is only 4kb, which can be problematic if you have many statements attached to the token.
Cookies may be vulnerable to attacks of cross-site request falsification (CSRF or XSRF). The use of CSRF protection from a web application framework makes cookies a safe option to store a JWT.
CSRF can also be partially prevented by checking the header HTTP Referer
and Origin
. You can also set the restricted cookie flag SameSite = Strict
(learn more), where with this policy, cookies cannot be sent to third party websites, which helps prevent CSRF attacks.
It can be difficult to implement if the application requires cross-domain access. Cookies have additional properties (Domain / Path) that can be modified to allow you to specify where the cookie can be sent.
References