DEV Community

Discussion on: JWT how does it work and is it secure?

Collapse
tbroyer profile image
Thomas Broyer • Edited on

About the conclusion of the article:

  • while cookies can be abused from XSS (e.g. session fixation with a cookie set from JS), they can't be exfiltrated if correctly used (with the HttpOnly flag), whereas your JWT in localStorage can be read by any JS, making XSS a much higher risk (well, in any case, if you have an XSS, it's gameover, unless maybe you actually only keep things in a non-global variable, i.e. not localStorage)
  • if you stored a session ID in localStorage, you'd mitigate CSRF the same
  • if you stored a JWT in a cookie, you'd be vulnerable to CSRF the same

It's not about what you use to authenticate your user, it's about how you put it.

Also, you're not tackling logout, aka revoking your JWT. To do that, you'll need to store things server-side and querying them on each client request. If your JWT tokens have a very short expiration (like the 2 minutes in your sample code), this is OK, but this will negatively impact UX (having to sign in again every 2 minutes) or security (keeping the user credentials in memory client-side).

About that sample code, you're not putting the user's password in the JWT are you ‽

About JWTs themselves, you can make an equivalent system (cryptographically sign, or encrypt by the way, some data that you also base64-encode) without the drawbacks of JWT (signature details "negotiation" through the JWT header).

Some reading about JWTs:

That last article also tackles the "accessing the database issue":

I continue to believe that boring, trustworthy random tokens are underrated, and that people burn a lot of complexity chasing statelessness they can't achieve and won't need, because token databases for most systems outside of Facebook aren't hard to scale.

Collapse
darken profile image
Achraf Affes Author

Thanks a lot for sharing your knowledge about the subject,
thanks for articles as well,

The post was a general presentation about JWT and the way it works and the main practices to make it more secure ( I admit as well that storing it in localStorage is risky unless we use short expiration time, which in some cases ruins the user experience )

I believe that using tokens vs cookies will always last as a huge debate, yet I admit that in some implementations, its better to use cookies over tokens for better user experience as you said.

Thanks again for sharing your knowledge about the subject.