sessionsingle-sign-onsingle-page-applicationjwt

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?


Solution

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