【问题标题】:NestJS include WWW-Authenticate header in jwt strategyNestJS 在 jwt 策略中包含 WWW-Authenticate 标头
【发布时间】:2021-10-21 16:26:38
【问题描述】:

我有一个有效的 nestjs 护照 JWT 策略,它返回一个 401 未经授权的无效或丢失承载令牌,但是,它没有设置响应标头 WWW-Authenticate 标头,我需要为期望的客户端库执行此操作标题中的那个

在我的 AuthModule 中我是这样注册的:

    JwtModule.register({
      secret: jwtConstants.secret,
      signOptions: { expiresIn: '1m' }
    })

我还将 JWT 策略描述如下:

import { ExtractJwt, Strategy } from 'passport-jwt';
import { jwtConstants } from './constants';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
    });
  }

  validate(payload: {
    sub: string;
    email: string;
  }): { userId: string; email: string } {
    return {
      userId: payload.sub,
      email: payload.email
    };
  }
}

如何设置 WWW-Authenticate 标头,仅在策略失败/返回 401 的情况下?

【问题讨论】:

    标签: jwt header nestjs


    【解决方案1】:

    我设法用一种稍微不同的方法来解决它,您可以使用异常过滤器来拦截身份验证失败,这对我有用,也许有人会发现它有用:

    @Catch(HttpException)
    export class HttpExceptionFilter implements ExceptionFilter {
      constructor() {}
    
      catch(exception: HttpException, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();
        const status = exception.getStatus();
    
        if (status === 401) {
          response.setHeader(
            'WWW-Authenticate',
            'Basic realm="Access to site", charset="UTF-8"',
          );
        }
        response.status(status).json(exception.getResponse());
      }
    }
    

    然后我可以在我的 main.ts 中全局实现它,如下所示:

    app.useGlobalFilters(new HttpExceptionFilter());
    

    【讨论】:

      猜你喜欢
      • 2020-06-09
      • 2016-06-02
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 2021-06-11
      • 2023-03-24
      • 2021-03-09
      相关资源
      最近更新 更多