我正在尝试利用AuthGuard
装饰器和护照 JWT 策略,遵循文档 https://docs.nestjs.com/techniques/authentication.
文档中的所有内容都运行良好。但我现在想保护 JWT 中包含的范围的路由。这是我的应用程序生成的基本 jwt 有效负载:
{
"user": {
"id": "20189c4f-1183-4216-8b48-333ddb825de8",
"username": "[email protected] /cdn-cgi/l/email-protection"
},
"scope": [
"manage_server"
],
"iat": 1534766258,
"exp": 1534771258,
"iss": "15f2463d-8810-44f9-a908-801872ded159",
"sub": "20189c4f-1183-4216-8b48-333ddb825de8",
"jti": "078047bc-fc1f-4c35-8abe-72834f7bcc44"
}
这是基本的保护路线,由AuthGuard
装饰器:
@Get('protected')
@UseGuards(AuthGuard('jwt'))
async protected(): Promise<string> {
return 'Hello Protected World';
}
我想添加选项并将该路线的访问限制为具有以下权限的人manager_server
范围进入他们的 JWT。所以在阅读了一些内容之后AuthGuard
代码,我认为我能够编写如下内容:
@Get('protected')
@UseGuards(AuthGuard('jwt', {
scope: 'manage_server'
}))
async protected(): Promise<string> {
return 'Hello Protected World';
}
但是,我在文档中看不到可以使用此选项的位置。
我认为添加一个选项参数validate
的功能JWTStrategy
可以成功,但事实并非如此。这是我的validate
函数(包含在jwt.strategy.ts
file):
async validate(payload: JwtPayload, done: ((err: any, value: any) => void)) {
const user = await this.authService.validateUser(payload);
if (!user) {
return done(new UnauthorizedException(), false);
}
done(null, user);
}
非常感谢您的帮助,如果您需要,请随时在评论中向我询问更多信息。