如何解决使用 JWT 策略的 NestJs 身份验证 - 添加“ignoreNotBefore”
我在 nestJs 中使用 AuthGuard 来验证请求 jwt 令牌。 因为我的服务只是验证token并没有创建它,所以它不能使用“nbf”验证,以避免出现创建token的服务器时间晚于我的服务器的情况。
当使用 jsonwebtoken 库处理纯 node.js 时,很容易添加选项来关闭此验证:
jwt.verify(token,cert,{ignoreNotBefore: true})
这也有效。 但是,我如何使用 nest 来做到这一点?
这是我的守卫:
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
constructor(private reflector: Reflector,private authService: AuthService) {
super();
}
async canActivate(context: ExecutionContext) {
const isValid = await super.canActivate(context);
return isValid;
}
handleRequest(err,user,info) {
if (err || !user) {
Logger.error(`Unauthorized: ${info && info.message}`);
throw err || new UnauthorizedException();
}
return user;
}
}
在 JWT 策略中,我尝试在调用 PassportStrategy 的“super”时添加 ignoreNotBefore 选项,但这不起作用:
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService,private config: ConfigService) {
super({
jwtFromrequest: ExtractJwt.fromAuthHeaderAsBearerToken(),ignoreExpiration: false,ignoreNotBefore: true,secretorKey: fs.readFileSync(config.get('auth.secret')),});
}
validate(payload: any) {
const isAuthorized = this.authConfig.roles.some((role) => payload.role?.includes(role));
if(!isAuthorized) {
Logger.error(`Unauthorized: Invalid role`);
throw new UnauthorizedException();
}
return true;
}
}
这样做的正确方法是什么?
谢谢。
解决方法
JwtAuthGuard
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService,private config: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),ignoreExpiration: false,jsonWebTokenOptions: {
// this object maps to jsonwebtoken verifier options
ignoreNotBefore: true,// ...
// maybe ignoreExpiration too?
},secretOrKey: fs.readFileSync(config.get('auth.secret')),});
}
validate(payload: any) {
const isAuthorized = this.authConfig.roles.some((role) => payload.role?.includes(role));
if(!isAuthorized) {
Logger.error(`Unauthorized: Invalid role`);
throw new UnauthorizedException();
}
return true;
}
}
说明
将您的 ignoreNotBefore
移至 jsonWebTokenOptions
,因为此对象映射到 jsonwebtoken
验证器选项。这是因为 Nest.js 包装了 passport-jwt
和 passport-jwt
包装了 jsonwebtoken
。所以根对象中的选项主要是配置策略(passport)而不是配置jsonwebtoken
(一样多)。
了解详情
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。