re: How to securely store JWT tokens. VIEW POST


One thing missing (from most web site authent. tutorials) is: how many tokens/sessions are currently allowed for a single user?
Because whatever the method [in your post], this does not prevent a whole range of issues.
Let's imagine you lend me your computer so that i can reserve a train, but instead go to DevTools and copy the cookie/localStorage/sessionStorage, i'm done in less than 30s and i can reuse the token whenever i want on my computer :)

If you want more security, you need to store a list of currently allowed signatures on server side.
This way you can:

  • check if user is already logged from somewhere else (physical location or other browser for instance)
  • restrict number of simultaneous sessions for a user
  • provide a way to revoke tokens to the user. See for instance in gmail : "Open in x other location · Details" and "Sign out all other Gmail web sessions" button

Note : do not store the whole token, otherwise if your database is compromised, tokens can be used to impersonate anyone...

This can be also completed with:

  • fingerprinting of the device (user agent, extensions...) to trust only some devices and trigger an alert for any untrusted device.
  • brute force prevention if someone tried to login but failed, take exponentially more time to respond (up to a few seconds) this requires thinking when scaling your web app on multiples nodes (ex: keep number of tentatives in a redis instances)

Hey Thibault,

Thanks for sharing all this info. All these things are really useful. Of course, they cannot be covered in a single tutorial, and it would also be out of the scope of the article.

I haven't implemented a solution that is so complex till now. Do you think that JWT tokens are a good solution for those cases? I mean, if you need to perform actions like checking if a user is logged in, JWT automatically loses a big advantage compared to traditional sessions, the ability to authenticate the user without any query to a DB server. Of course, you keep the authentication stateless but this can be achieved with generated ids that identify the user session (stateless session) too. What's your opinion on these subjects?


I'm not experienced enough to give you a definitive answer.

Managing traditional sessions isn't that simple either, especially when you want the "remember me" feature. By implementing things yourself, you're likely to open doors.
Thus, a JWT library with stateless session definitely brings advantages. I also like the encoded payload+signature compared to a lot of things seen in cookies :p

So maybe using JWT and storing only the signature in a table with a foreign key on the user would be interesting.

  • Checks are only made during authentication.
  • Every other http call is stateless
code of conduct - report abuse