4 ms·
What I do: I use tokens (rather than cookies), but I don't use JWT, for some of the reasons listed in the post, such as "can't expire" and "data goes stale". In
by pfooti 10y ago
What I do: I use tokens (rather than cookies), but I don't use JWT, for some of the reasons listed in the post, such as "can't expire" and "data goes stale". Instead, after authenticating a user, I issue a long piece of random (256 bits of random packed into a base64 string) to the user. I use the same string as a redis key whose value is the actual user ID of the authenticated user.
That way the front end can pass the token to the back end, I can authenticate and authorize using the redis data (I could store more data in redis, but instead I hit postgres for any other data about the user, such as admin roles, when needed during the authorization process).
It's true that this doesn't make you invincible to CSRF or XSS - any attacker who goes through the trouble and gets access to the token via MITM (although I only use HTTPS, that's not a guarantee) or by injecting javascript in the webapp itself (through user-editable content from a malicious user), that attacker suddenly has full access to the user's account. Still, it's a pretty reasonable way to deal with session problems.
I also set expiry timeouts on these tokens and can delete them manually if a user wants to end all sessions (say on password change). Deleting by value match isn't super-straightforward in redis, but it's also possible with a bit of LUA.
- monknomo 10y agoI thought you could include a tamper-proof expiration time in the payload of a JWT token? It also seems like data-staleness could be addressed, perhaps by including a hash of relevant data and invalidating/reissuing a token when the hash changes?
- pfooti 10y agoYou can include a tamper-proof expiration time in JWT, but you cannot early-expire or extend that JWT easily (you could always pass back a new, extended one transparently). But in my system, I just keep expiring the redis key for 25 hours from now each time I touch it, so users' authentications expire after 25 hours (after which point they have to go back through username/password or OAUTH, etc). You can easily change 25 hours to 4 days or a month or whatever.
- bdamm 10y agoCSRF isn't about content injection or acquisition of session tokens. I think you probably know that but the way you describe "doesn't make you invincible" I'd say a little more strongly; it doesn't do anything at all to prevent CSRF (or XSS!)
- joepie91_ 10y agoWhile that sounds fairly similar to most session implementations, I would recommend using a battle-tested implementation rather than using your own, if at all possible.