[我尝试在警卫/装饰员的帮助下先检查JWT,然后再检查用户的角色。
我已经阅读了有关身份验证,防护和装饰器的文档,并了解其背后的原理。
但是,我无法做的是使JWT-Guard的经过身份验证的用户可用于Roles-Guards。
在我发现的每个示例中,对我来说很有趣的这一部分都被跳过/遗漏了...
感谢每一个小费!
这是我最近的尝试:
jwt.strategy.ts
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { JwtPayload } from './jwt.model';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
passReqToCallback: true,
ignoreExpiration: false,
secretOrKey: '0000',
expiresIn: '3 days'
});
}
async validate(payload: JwtPayload) {
return {
id: payload.id,
email: payload.email,
username: payload.username
};
}
}
roles.guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {
}
canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.get<string[]>('roles', context.getHandler());
if (!roles) {
return false;
}
const request = context.switchToHttp().getRequest();
const user = request.user ??? // THIS is what is missing
return roles.some((role) => {
return role === user.role;
});
}
}
roles.decorator.ts
import { SetMetadata } from '@nestjs/common';
export const Roles = (...roles: string[]) => SetMetadata('roles', roles);
users.controller.ts
@UseGuards(AuthGuard('jwt'))
@Roles('admin', 'member')
@Get('/')
async doSomething(@Req() req): Promise<User> {
return await this.usersService.doSomething(req.user.id);
}
您的装饰器和守护程序看起来不错,但是从users.controller.ts
文件的片段中,不清楚是否确实为GET /
路由应用了角色守护程序。
但是,我有一个基于guards documentation的NestJS应用程序,其设置非常相似。 users.controller.ts
中的以下代码按预期工作:
@UseGuards(JwtAuthGuard, RolesGuard)
@Controller('/users')
export class UserController {
constructor(private readonly userService: UserService) {}
@Get()
@Roles(UserRole.ADMIN)
public async index(): Promise<User[]> {
return this.userService.findAll();
}
// ...
}
请注意,如何在同一范围内激活auth和角色保护,并在之前 JwtAuthGuard
添加RolesGuard
。如果我要更改防护的顺序,则RolesGuard
将无法检索请求的用户。
此外,您可能还想了解一下a similar question,其中包含有关不同作用域的保护顺序的详细信息。