Our current app uses HTTP sessions and we'd like to replace that with JWT.
The setup allows only a single session per user. This means:
This works because there's a server-side relation between session id and user id.
Using JWT I could imagine to have some counter inside the user database, which gets increased with every login, i.e.:
Now with every request I have to check if the incoming signature is correct for the current counter value.
This somehow makes it stateful. :(
But ... one of JWT's benefits is, that there's no need to access any database or session store for validating the token.
Is there some other solution for preventing concurrent logins? Maybe something that works without database access and keeps it stateless?
The solution is to not use JWT at all for session purposes. But instead, do the traditional, but battle-tested way more efficiently. I.e. make the database lookup so blazing fast (sub-millisecond) that the additional call won't matter.
One of the “issues” with sessions is scalability. The argument is that sessions are stored in memory and servers are duplicated to handle the application load, therefore, limiting the scalability of the application. JWT, on the other hand, has higher scalability due to its statelessness.
JWT is a particularly useful technology for API authentication and server-to-server authorization.
Because the user receives a JWT after a successful login, which contains all important information about the user. This means that the session no longer has to be saved on the server and is therefore also called a stateless session.
You are very close to the solution.
To do this you need the following:
1. Include iat in the token (Time when the token was issued)
2. Somewhere store the time when the user last logged in, for example in the user's profile.
Now when validating the token, do an extra check: iat (Issued At) must be at or later than the last login time. This implicitly invalidates older tokens.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With