If you are using JWT as an authentication token, it should be stored as a cookie marked httpOnly
and secure
, as apposed to using Local/Session Storage. As you mention, this protects against XSS attacks, where we are concerned about malicious JavaScript being injected into our page and stealing our session token.
- A cookie marked
httpOnly
cannot be read by JavaScript, so it cannot be stolen in an XSS attack.
- Local/Session Storage, however, can be read by JavaScript, so putting the session token there would make it vulnerable to an XSS attack.
However, making the session token cookie httpOnly
and secure
still leaves you vulnerable to CSRF attacks. To see why, remember that cookies are marked with the domain from which they originated, and the browser only sends cookies that match the domain to which the request is being sent (independent of the domain of the page the request was sent from). For example, suppose I'm signed into stackoverflow.com
in one tab, and in another tab go to evil.com
. If evil.com
makes an ajax call to stackoverflow.com/delete-my-account
, my stackoverflow authentication token cookie will be sent to the stackoverflow server. Unless that endpoint is protecting against CSRF, my account will be deleted.
There are techniques for preventing CSRF attacks. I would recommend reading this OWASP page on CSRF attacks and preventions.