Invalidating JSON Web Tokens

前端 未结 28 2397
夕颜
夕颜 2020-11-22 06:17

For a new node.js project I\'m working on, I\'m thinking about switching over from a cookie based session approach (by this, I mean, storing an id to a key-value store conta

28条回答
  •  北海茫月
    2020-11-22 07:05

    If you want to be able to revoke user tokens, you can keep track of all issued tokens on your DB and check if they're valid (exist) on a session-like table. The downside is that you'll hit the DB on every request.

    I haven't tried it, but i suggest the following method to allow token revocation while keeping DB hits to a minimum -

    To lower the database checks rate, divide all issued JWT tokens into X groups according to some deterministic association (e.g., 10 groups by first digit of the user id).

    Each JWT token will hold the group id and a timestamp created upon token creation. e.g., { "group_id": 1, "timestamp": 1551861473716 }

    The server will hold all group ids in memory and each group will have a timestamp that indicates when was the last log-out event of a user belonging to that group. e.g., { "group1": 1551861473714, "group2": 1551861487293, ... }

    Requests with a JWT token that have an older group timestamp, will be checked for validity (DB hit) and if valid, a new JWT token with a fresh timestamp will be issued for client's future use. If the token's group timestamp is newer, we trust the JWT (No DB hit).

    So -

    1. We only validate a JWT token using the DB if the token has an old group timestamp, while future requests won't get validated until someone in the user's group will log-out.
    2. We use groups to limit the number of timestamp changes (say there's a user logging in and out like there's no tomorrow - will only affect limited number of users instead of everyone)
    3. We limit the number of groups to limit the amount of timestamps held in memory
    4. Invalidating a token is a breeze - just remove it from the session table and generate a new timestamp for the user's group.

提交回复
热议问题