#StackBounty: #jwt #multi-tenant #nestjs how to recognized jwt token from different tenant nestjs muti-tenant jwt

Bounty: 100

I implement multi-tenant by multiple databases and use jwt token as authorization, my concern is that when user 1 of tenant 2 login and get the jwt token, when he uses to token to access another tenant, does he recognized as user 1 of tenant 2? If so, how can we fix it?

My Strategy


export class JwtStrategy extends PassportStrategy(Strategy) {
    private readonly configService: ConfigService,

    private readonly moduleRef: ModuleRef,
  ) {
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      passReqToCallback: true,
      secretOrKey: configService.get('JWT_SECRET_KEY'),

  async validate(request: Request, jwtPayload: JwtPayload) {
    const contextId = ContextIdFactory.getByRequest(request);

    const authService: AuthService = await this.moduleRef.resolve(

    let { iat, exp } = jwtPayload;
    const timeDiff = exp - iat;

    if (timeDiff <= 0) {
      throw new UnauthorizedException();
    return jwtPayload;

My Auth Service


@Injectable({ scope: Scope.REQUEST })
export class AuthService {
    private readonly jwtService: JwtService,
    private readonly configService: ConfigService,
    private readonly userService: UsersService,
    private readonly auctionHouseService: AuctionHouseService,
  ) {}

  async createToken(user: User) {
    let plainUser: any = Object.assign({}, user);
    plainUser.auctionHouseId = (
      await this.auctionHouseService.getCurrentAuctionHouse()
    return {
      expiresIn: this.configService.get('JWT_EXPIRATION_TIME'),
      accessToken: this.jwtService.sign(plainUser),


My Login controller


export class AuthController {
    private readonly authService: AuthService,
    private readonly userService: UsersService,
  ) {}

  @ApiResponse({ status: 201, description: 'Successful Login' })
  @ApiResponse({ status: 400, description: 'Bad Request' })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  async login(@Body() payload: LoginPayload, @Req() req): Promise<any> {
    let user = await this.authService.validateUser(payload);

    return omitPassword(await this.authService.createToken(user));

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.