目前,我已经设法使用AuthGuard进行JWT身份验证,但我无法在user
上获得Roles
。
我试图跟随猫example,但我从来没有定义user
对象,你可以在第14行看到。
这是我的代码:
// auth.controller.ts
@Controller('auth')
@UseGuards(RolesGuard)
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Get('token')
async createToken(): Promise<any> {
return await this.authService.createToken();
}
@Post()
@UseGuards(AuthGuard())
@Roles('admin')
findAll() {
// this route is restricted by AuthGuard
// JWT strategy
return 'Super important info';
}
}
// auth.module.ts
@Module({
imports: [
SharedModule,
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.registerAsync({
imports: [SharedModule],
useFactory: async (configService: ConfigService) => ({
secretOrPrivateKey: configService.get('SECRET_KEY'),
signOptions: {
expiresIn: configService.get('SECRET_KEY_EXPIRES'),
},
}),
inject: [ConfigService],
}),
],
controllers: [AuthController],
providers: [
AuthService,
JwtStrategy,
],
})
export class AuthModule {}
其余所有内容都与存储库中的示例完全相同。任何想法如何能够定义users
?
AuthGuard()
必须在RolesGuard
之前运行,以便您通过身份验证并设置user
属性。
据我所知,没有其他方法可以改变你的守卫的顺序,然后将它们定义为:
@UseGuards(AuthGuard(), RolesGuard)
讨论了在这个qazxsw poi中改变守卫执行层次的潜在API。
这个issue提到了另一种解决方案:
对于这个用例,我觉得将认证逻辑放在中间件中会更好,因为它在守卫之前运行。