Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JWT and one(!) session per user / no concurrent sessions

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:

  1. User signs in at Device 1
    • User is logged in at Device 1 (new Session created)
  2. User signs in at Device 2
    • User is logged in at Device 2 (new Session created)
    • User is not logged in at Device 1 (Session got destroyed)

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.:

  1. User signs in at Device 1
    • JWT tokens signature contains counter+1 (and save new counter to database)
  2. User signs in at Device 2
    • JWT's signature contains counter+1 and it gets increased and saved to db.

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?

like image 435
Benjamin M Avatar asked Feb 23 '15 21:02

Benjamin M


People also ask

Can I use both session and JWT?

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.

What is the difference between sessions and JWTs?

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.

Is JWT good for user authentication?

JWT is a particularly useful technology for API authentication and server-to-server authorization.

Why is JWT called stateless?

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.


1 Answers

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.

like image 185
The Tahaan Avatar answered Sep 22 '22 04:09

The Tahaan