我通过多个数据库实现多租户并使用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));
}
aud
(或受众)字段。每RFC7519: