#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

jwt.strategy.ts


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

    private readonly moduleRef: ModuleRef,
  ) {
    super({
      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(
      AuthService,
      contextId,
    );

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

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

My Auth Service

auth.service.ts


@Injectable({ scope: Scope.REQUEST })
export class AuthService {
  constructor(
    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()
    ).id;
    return {
      expiresIn: this.configService.get('JWT_EXPIRATION_TIME'),
      accessToken: this.jwtService.sign(plainUser),
    };
  }

}

My Login controller

auth.controller.ts


@Controller('api/auth')
@ApiUseTags('authentication')
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly userService: UsersService,
  ) {}

  @Post('login')
  @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.