NestJS的JWT策略校验失败返回401时如何添加WWW-Authenticate响应头
解决方案
你可以通过自定义JWT认证守卫,在捕获到JWT校验失败抛出的401异常时,主动往响应头添加WWW-Authenticate字段,具体实现步骤如下:
步骤1:实现自定义JwtAuthGuard
首先创建继承自默认AuthGuard('jwt')的自定义守卫,重写handleRequest方法,在校验失败返回401时设置响应头:
import { ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { Response } from 'express'; @Injectable() export class JwtAuthGuard extends AuthGuard('jwt') { handleRequest(err: any, user: any, info: any, context: ExecutionContext) { // 校验失败:err存在或者user为空时,说明JWT校验不通过 if (err || !user) { const response = context.switchToHttp().getResponse<Response>(); // 设置WWW-Authenticate响应头,可根据需求调整realm、错误描述等参数 response.setHeader('WWW-Authenticate', 'Bearer realm="your_service_realm", error="invalid_token", error_description="The access token is invalid or missing"'); throw err || new UnauthorizedException(); } return user; } }
如果你项目使用的是Fastify而非Express,只需要修改获取响应和设置头的对应API即可,整体逻辑不变。
步骤2:替换原有默认的AuthGuard
把之前代码中使用@UseGuards(AuthGuard('jwt'))的位置,全部替换为使用自定义的JwtAuthGuard即可:
// 控制器中使用示例 @Get('protected') @UseGuards(JwtAuthGuard) getProtectedResource() { return 'this is protected data'; }
额外说明
上述实现只会在JWT策略校验失败返回401时添加响应头,不会影响其他业务逻辑主动抛出的401响应,完全符合你的场景要求。
内容的提问来源于stack exchange,提问作者edencorbin
相关产品推荐
相关产品推荐

