如何在 Nestjs 中授权时提取 JWT



我的目的是制作一个角色保护来验证用户的权限。我尝试提取授权标头以获取 JWT 中包含的角色信息。我实现了canActivate接口来检查使用角色,但我不知道如何从 JWT 获取角色信息进行验证。

export class RolesGuard implements CanActivate {
constructor(private readonly _reflector: Reflector) {
}
canActivate(context: ExecutionContext): boolean {
const roles = this._reflector.get<UserRole[]>(
'roles',
context.getHandler(),
);
if (!roles || roles.length === 0) {
return true;
}
const request = context.switchToHttp().getRequest();
const user: InstanceType<User> = request.headers.role;
// i want to get the role from JWT in here
const hasRole = () => roles.indexOf(user.role) >= 0;
if (user && user.role && hasRole()) {
return true;
}
throw new HttpException(
'You do not have permission (Roles)',
HttpStatus.UNAUTHORIZED,
);
}
}

我尝试扩展PassportStrategy,但它不能与CanActive一起使用

一种选择是使用JwtModule中的JwtService并使用jwtService.decode(myJwt)获取解码的 JWT 并从那里获取角色。另一种是使用内置的护照卫士(AuthGuard(,扩展功能,并在自定义逻辑之前调用super.canActivate(context)。存储结果并立即检查用户是否具有护照访问权限,然后再继续使用自定义逻辑。

// the mention of jwt in the AuthGuard is only needed if not working with defaultStrategy
export class RolesGuard extends AuthGuard('jwt') {
constructor(private readonly _reflector: Reflector) {
super()
}
canActivate(context: ExecutionContext): boolean {
const passportActive = super.canActivate(context);
if (!passportActivate) {
throw new HttpException(
'You do not have permission (Roles)',
HttpStatus.UNAUTHORIZED,
);
}
const roles = this._reflector.get<UserRole[]>(
'roles',
context.getHandler(),
);
if (!roles || roles.length === 0) {
return true;
}
const request = context.switchToHttp().getRequest();
// this should come from passport
const user: InstanceType<User> = request.user;
// i want to get the role from JWT in here
const hasRole = () => roles.indexOf(user.role) >= 0;
if (user && user.role && hasRole()) {
return true;
}
throw new HttpException(
'You do not have permission (Roles)',
HttpStatus.UNAUTHORIZED,
);
}
}

相关内容

  • 没有找到相关文章