use*_*448 2 node.js nestjs nestjs-jwt
我在 NestJs 中使用 AuthGuard 来验证请求 jwt 令牌。因为我的服务只是验证令牌而不是创建它,所以它不能使用“nbf”验证,以避免创建令牌的服务器的时间晚于我的服务器的情况。
当使用 jsonwebtoken 库使用纯 Node.js 时,可以轻松添加选项来关闭此验证,方法是添加:
jwt.verify(token, cert, {ignoreNotBefore: true})
Run Code Online (Sandbox Code Playgroud)
这也有效。但是,我该如何使用 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;
}
}
Run Code Online (Sandbox Code Playgroud)
在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;
}
}
Run Code Online (Sandbox Code Playgroud)
这样做的正确方法是什么?
谢谢。
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
将您的移动ignoreNotBefore
到,jsonWebTokenOptions
因为该对象映射到jsonwebtoken
验证程序选项。这就像 Nest.js 已经wrappedpassport-jwt
和passport-jwt
wrapps一样jsonwebtoken
。所以根对象中的选项主要是配置策略(护照)而不是配置jsonwebtoken
(那么多)。
归档时间: |
|
查看次数: |
12988 次 |
最近记录: |