微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 JWT 策略的 NestJs 身份验证 - 添加“ignoreNotBefore”

如何解决使用 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-jwtpassport-jwt 包装了 jsonwebtoken。所以根对象中的选项主要是配置策略(passport)而不是配置jsonwebtoken(一样多)。

了解详情

  1. http://www.passportjs.org/packages/passport-jwt/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?