Ham*_*bot 13 javascript node.js nestjs
我正在尝试AuthGuard
按照文档使用装饰器和通行证 JWT 策略。
文档中的所有内容都很好用。但是我现在想保护具有包含在 JWT 中的范围的路由。所以这是我的应用程序生成的基本 jwt 负载:
{
"user": {
"id": "20189c4f-1183-4216-8b48-333ddb825de8",
"username": "user.test@gmail.com"
},
"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"
}
Run Code Online (Sandbox Code Playgroud)
这是AuthGuard
装饰器保护的基本受保护路由:
@Get('protected')
@UseGuards(AuthGuard('jwt'))
async protected(): Promise<string> {
return 'Hello Protected World';
}
Run Code Online (Sandbox Code Playgroud)
我想添加选项并将该路由的访问权限限制为具有manager_server
JWT 范围的人员。所以在阅读了一些AuthGuard
代码之后,我认为我可以写出类似的东西:
@Get('protected')
@UseGuards(AuthGuard('jwt', {
scope: 'manage_server'
}))
async protected(): Promise<string> {
return 'Hello Protected World';
}
Run Code Online (Sandbox Code Playgroud)
但是,我在文档中看不到可以使用此选项的地方。
我认为向 the 的validate
函数添加一个选项参数JWTStrategy
可以解决问题,但事实并非如此。这是我的validate
函数(包含在jwt.strategy.ts
文件中):
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);
}
Run Code Online (Sandbox Code Playgroud)
非常感谢您的帮助,如果您需要,请随时在评论中向我询问更多信息。
Kim*_*ern 13
当您查看AuthGuard的代码时,似乎该options.callback
功能是唯一可能的自定义。
我认为AuthGuard
与其编写自己的支持范围检查的内容,不如拥有一个ScopesGuard
(或RolesGuard
)自己的装饰器,@Scopes('manage_server')
而不是像这样的装饰器。为此,您只需按照docs 中的RolesGuard
示例进行操作,该示例也只检查请求中属性下的 JWT 负载的属性。user
创建@Scopes()
装饰器:
export const Scopes = (...scopes: string[]) => SetMetadata('scopes', scopes);
Run Code Online (Sandbox Code Playgroud)
创建一个ScopesGuard
:
@Injectable()
export class ScopesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const scopes = this.reflector.get<string[]>('scopes', context.getHandler());
if (!scopes) {
return true;
}
const request = context.switchToHttp().getRequest();
const user = request.user;
const hasScope = () => user.scopes.some((scope) => scopes.includes(scope));
return user && user.scopes && hasScope();
}
}
Run Code Online (Sandbox Code Playgroud)
使用 ScopesGuard 作为所有路由的全局保护(当没有给出范围时返回 true):
@Module({
providers: [
{
provide: APP_GUARD,
useClass: ScopesGuard,
},
],
})
export class ApplicationModule {}
Run Code Online (Sandbox Code Playgroud)
然后在端点上使用它:
@Get('protected')
@UseGuards(AuthGuard('jwt'))
@Scopes('manage_server')
async protected(): Promise<string> {
return 'Hello Protected World';
}
Run Code Online (Sandbox Code Playgroud)
小智 7
我尝试了一种稍微不同的方法,通过扩展 AuthGuard 保护。我想保持使用不同 Passport 策略的能力,所以我包含了一个 mixin。反馈表示赞赏。
在您的 Jwt 策略中,您可以简单地返回 JwtPaylozd,以便用户具有 scopes 属性。然后自定义 AuthGuard 如下所示:
import { UnauthorizedException, mixin } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
export function AuthScopes(scopes: string[], type?: string | string[]) {
return mixin(class ScopesAuth extends AuthGuard(type) {
protected readonly scopes = scopes;
handleRequest(err, user, info, context) {
if (err || !user) {
throw err || new UnauthorizedException();
}
if(!this.scopes.some(s => user.scopes.split(' ').includes(s)))
{
throw new UnauthorizedException(`JWT does not possess one of the required scopes (${this.scopes.join(',')})`);
}
return user;
}
});
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用这个守卫:
@Get('protected')
@UseGuards(AuthScopes(['secret:read'], 'jwt'))
async protected(): Promise<string> {
return 'Hello Protected World';
}
Run Code Online (Sandbox Code Playgroud)
'jwt' 代表策略。
归档时间: |
|
查看次数: |
13446 次 |
最近记录: |