jsonwebtoken-redis
This library completely repeats the entire functionality of the library jsonwebtoken, with four important additions:
- The token expiration time can be completely managed by Redis.
- You can invalidate the token by removing it from Redis.
- You can postpone the expiration a token.
- There's no callback. All functions returns Promises.
Installation
npm install jsonwebtoken-redis
Quick start
const Redis = ;const redis = ;const JwtRedis = ; const jwtRedis = redis prefix: 'session:' // The prefix used in Redis keys (optional). Defaults to "session:". expiresKeyIn: '24 hours' // The default Redis expiration time (optional) promiseImpl: Promise // Custom promise library (optional). Defaults to native Promise.; const secret = 'shhhhhh';const payload = scope: 'user' user: '1'; // Sign function call overriding the default Redis expiration time provided abovejwtRedis;
Expiration time managed by Redis
There's a new option expiresKeyIn
when you call sign.
This option is used to set the expiration time of the key/value created in Redis.
Using this option the expiration time is completely managed by Redis, in other words, the key/value is created in Redis through the command expire
. The token it self doesn't contain any expiration data.
jwtRedis;
You can continue to use the option expiresIn
or the payload attribute exp
, but the option expiresKeyIn
will be completely ignore.
The key/value will be created in Redis with the expiration based on jwt option or payload attriute mentioned previously.
Attention: Implementing this way, you can't postpone the expiration in Redis because the token it self will expire.
Defining the jti claim
The "jti" (JWT ID) claim provides a unique identifier for the JWT. This is used to create the key for the token in Redis. If you don't provide the "jti", a new one will be generated using uuid version 4 (random).
const jwtRedis = client prefix: 'session:'const payload = jti: 'test'; // The key for the token in Redis will be "session:test"const secret = 'shhhhhh';jwtRedis;
Touching the token
When you set the jwt expiration time, you can't change it anymore. By using the option expiresKeyIn
when you call sign
, you have the power to postpone the expiration time.
jwtRedis;// After 30 minutes...jwtRedis;
Destroying the token
You can invalidate the token by calling destroy
function. This will remove the key/value associated to the token from Redis.
All future calls to verify
will throw JwtRedis.TokenExpiredError
.
jwtRedis;
Promises
All functions will return a Promise. You can set the Promise implementation by passing the option promiseImpl
when you instantiate a new JwtRedis
.
const Promise = const jwtRedis = redis promiseImpl: Promise;
API
Create a token
jwtRedis.sign(payload, secretOrPrivateKey [, options])
Verify the token
jwtRedis.verify(token, secretOrPublicKey [, options])
Decode the token
jwt.decode(token [, options])
Postpone the token expiration
jwtRedis.touch(token)
Destroy the token