SWASTIJ CONSULTANCY

Invalidate jwt token using jwt-redis & nest js

There are a few ways to invalidate a JSON Web Token (JWT).


Use cases

There are multiple methods of invalidating a JWT token. Each way caters to a different use case, which is described here:

  1. Invalidate all: If you need to invalidate all existing JWTs, then changing the secret is the simplest option.
  2. Time bomb: If you want to revoke access to a user's account after a certain period, then adding an expiration date is a good option.
  3. Invalidate specific token: If you need to revoke access to a user's account immediately, then blacklisting the token is the best option.

Here are some additional details about each method:

It is important to note that JWTs are designed to be stateless. This means that the server does not need to keep track of which users have valid tokens. However, if you need to invalidate JWTs, then you will need to keep track of which tokens have been invalidated. This can be done by storing the invalidated tokens in a database or by using a blacklist.

What about the latency of blacklist database lookup?

Can the database lookup be made so fast that the existence of this additional database doesn’t matter? YES! Redis is the answer. It can serve millions of requests in sub-milliseconds.


Invalidating jwt tokens with jwt-redis Nest js

Redis is a popular in-memory data store that is often used for caching and session management. jwt-redis makes it easy to store JWT tokens in Redis so that you can easily invalidate them when they expire or are revoked. 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. This makes it possible to make a token not valid until it expires. jwt-redis supports node_redis client.

jwt-redis uses the blacklist method (described above) behind the scenes.

To use jwt-redis, you first need to install it with npm:

 npm install jwt-redis

Once you have installed jwt-redis, you can start using it to store JWT tokens. Here is an example:

 import { createClient, RedisClientType } from 'redis';
import JWTR from 'jwt-redis';

@Injectable()
export class LocalJwtService {
private redisClient: RedisClientType ;
private secret ;
private jwtr;

constructor() {
	this.redisClient = createClient();
	this.secret = 'SECRET';
	this.redisClient.connect().then(() => {
		this.jwtr = new JWTR(this.redisClient);
	}).catch((e)=>{
		console.log(e);
	});
}

async sign(payload) {
	try {
		return await this.jwtr.sign(payload, this.secret);
	} catch (e) {
		console.log(e);
		return await handleSendFallbackError(e, 'Failed to sign token');
	}
}

async verify(payload) {
	try {
		await this.jwtr.verify(payload, this.secret);
		return this.jwtr.decode(payload);
	} catch (e) {
		console.log(e);
		return new UnauthorizedException();
	}
}

	async destroy(payload) {
		try {
			return await this.jwtr.destroy(payload);
		} catch (e) {
			console.log(e);
			return await handleSendFallbackError(e, 'Failed to destroy token');
		}
	}
}

If you are using JWTs for authentication, then jwt-redis can help you to improve the security of your application by making it easy to invalidate expired or revoked tokens.