如何从不同的承租人nestjs多租户jwt识别jwt令牌

问题描述 投票:0回答:1

我通过多个数据库实现多租户并使用jwt令牌作为授权,我担心的是,当租户2的用户1登录并获得jwt令牌时(当他用来令牌访问另一个租户时,他是否识别为用户1)租户2?如果是这样,我们如何解决它?

我的策略

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;
  }
}

我的身份验证服务

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),
    };
  }

}

我的登录控制器

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));
  }

jwt multi-tenant nestjs
1个回答
1
投票
通常,标识JWT有效域的正确方法是aud(或受众)字段。每RFC7519
© www.soinside.com 2019 - 2024. All rights reserved.