sessionredissession-state

Storing sessions in Redis while being able to revoke all sessions of a user


When a user authenticates on my website, either via email & password or OAuth (Google, Apple, Facebook...), I create a cookie with the session id of the user and store the session data in Redis.

The session data is the following (it gets serialised as a string):

{
  "id": "random_session_id",
  "iat": 1677004020931,
  "userId": "id_of_the_user_who_owns_the_session",
  "device": "Samsung s10",
  "ip": 0.0.0.0,
}

And it's stored with the id as the Redis key and an expiration time, which is the same as the maxAgeInSeconds property of the cookie obviously.

My issue is that I need to invalidate all the sessions of a user when he resets his password. To do that I thought of storing the sessions with hashes in Redis, like so:

 - user_id
   |--> session_id_1
        |--> session_data_serialised
   |--> session_id_2
        |--> another_session_data_serialised
 - user_id_2
   |--> session_id_3
        |--> session_data_serialised
   |--> session_id_4
        |--> session_data_serialised

The issue with this approach is that you cannot set an expiration on hashes in Redis, so this is not an option for me.

I then though of creating another cache where I put all the sessions of each user but then I also need to remove the entries from this cache when the session expires and it doesn't seem possible.

How should I achieve my goal here?


Solution

  • I think you can make it simpler redis structure.

    Example scenario:

    It is the visualization of redis structure, this using Redis Strings

    112233:${mobile session id}

    112233:${desktop session id}

    So how to invalidate all the sessions of a user when he resets his password? for example you cane use this command (or you can use search pattern to more safe)

    DEL 112233:*

    and the expiration of keys works well in this structure.