Invalidating JSON Web Tokens

前端 未结 28 2772
夕颜
夕颜 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 06:48

    ------------------------Bit late for this answer but may be it will help to someone------------------------

    From the Client Side, the easiest way is to remove the token from the storage of browser.

    But, What if you want to destroy the token on the Node server -

    The problem with JWT package is that it doesn't provide any method or way to destroy the token. You may use different methods with respect to JWT which are mentioned above. But here i go with the jwt-redis.

    So in order to destroy the token on the serverside you may use jwt-redis package instead of JWT

    This library (jwt-redis) completely repeats the entire functionality of the library jsonwebtoken, with one important addition. Jwt-redis allows you to store the token label in redis to verify validity. The absence of a token label in redis makes the token not valid. To destroy the token in jwt-redis, there is a destroy method

    it works in this way :

    1) Install jwt-redis from npm

    2) To Create -

    var redis = require('redis');
    var JWTR =  require('jwt-redis').default;
    var redisClient = redis.createClient();
    var jwtr = new JWTR(redisClient);
    
    jwtr.sign(payload, secret)
        .then((token)=>{
                // your code
        })
        .catch((error)=>{
                // error handling
        });
    

    3) To verify -

    jwtr.verify(token, secret);
    

    4) To Destroy -

    jwtr.destroy(token)
    

    Note : you can provide expiresIn during signin of token in the same as it is provided in JWT.

    May be this will help to someone

提交回复
热议问题