【问题标题】:NestJs authentication with JWT strategy - add validation option of "ignoreNotBefore"使用 JWT 策略的 NestJs 身份验证 - 添加“ignoreNotBefore”的验证选项
【发布时间】:2021-08-15 15:09:37
【问题描述】:

我在 NestJs 中使用 AuthGuard 来验证请求 jwt 令牌。 由于我的服务只是验证令牌而不是创建它,它不能使用“nbf”验证以避免创建令牌的服务器时间晚于我的服务器的情况。

当使用 jsonwebtoken 库处理纯 node.js 时,很容易通过添加以下选项来关闭此验证:

jwt.verify(token, cert, {ignoreNotBefore: true})

这也有效。 但是,我怎样才能使用嵌套呢?

这是我的后卫:

    @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;
  }
}

这样做的正确方法是什么?

谢谢。

【问题讨论】:

    标签: node.js nestjs nestjs-jwt


    【解决方案1】:

    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。所以根对象中的选项主要是配置策略(护照),而不是配置jsonwebtoken(一样多)。

    了解详情

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

    【讨论】:

      猜你喜欢
      • 2020-04-20
      • 2019-04-30
      • 2019-03-28
      • 2019-01-26
      • 2018-12-01
      • 2021-03-02
      • 2022-07-19
      • 2019-09-13
      • 2020-06-08
      相关资源
      最近更新 更多