目前,我已成功将 AuthGuard 与 JWT 身份验证结合使用,但无法在 Angular 色
上获取用户
。
我尝试过跟随猫 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 {}
其余部分与存储库中的示例完全相同。知道如何定义用户
吗?
最佳答案
AuthGuard()
必须在 RolesGuard
之前运行,以便您通过身份验证并设置 user
属性。
据我所知,除了将它们定义为:
之外,没有其他方法可以更改守卫的顺序@UseGuards(AuthGuard(), RolesGuard)
在此 issue 中讨论了用于更改守卫执行层次结构的潜在 API .
<小时/>这个issue提到了替代解决方案:
for this use case, i feel like putting authentication logic in a middleware would be better, as it runs before the guard.
关于javascript - NestJS - 如何将 RoleGuard 与 JWT 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55476665/