NestJS Swagger UI重复显示Authorization字段问题求助
问题描述
在NestJS的TypeScript控制器方法中,使用@Headers("Authorization")注入请求头功能正常,但Swagger会自动将该请求头解析为必填参数展示在Parameters区域,且该区域输入的值不会随请求发送。同时已通过main.ts配置Swagger全局Bearer认证(顶部"Authorize"按钮),输入的Token可正常携带,导致Parameters区域的Authorization字段多余且无效。
当前配置代码(main.ts):
const config = new DocumentBuilder() .setTitle("Some API") .setDescription("The API") .setVersion('1.0') .addBearerAuth({ type: "http", scheme: "bearer", bearerFormat: "JWT", in: "header", name: "JWT", description: "Enter your Bearer token", }, "Authorization") .addSecurityRequirements("Authorization") .build(); const documentFactory = () => SwaggerModule.createDocument(app, config); SwaggerModule.setup("v1/api", app, documentFactory);
控制器代码片段:
@Controller() @Injectable() export class UserCredentialController { @Get(`/v1/auth/readlogin`) async getOwnUserLoginInfo(@Headers("Authorization") authHeader: string) { if (!authHeader) { throw new UnauthorizedException("No authorization header found"); } // 业务逻辑省略 } // 其他方法省略 }
解决方案
方法1:用Swagger注解隐藏参数
直接在@Headers()装饰器上方添加@ApiHideProperty(),告知Swagger忽略该参数的展示:
import { ApiHideProperty } from '@nestjs/swagger'; // ... @Get(`/v1/auth/readlogin`) async getOwnUserLoginInfo( @ApiHideProperty() // 添加此注解隐藏Swagger中的参数展示 @Headers("Authorization") authHeader: string ) { // 业务逻辑 }
若@ApiHideProperty不生效,可改用@ApiParam明确标记参数隐藏:
import { ApiParam } from '@nestjs/swagger'; // ... @Get(`/v1/auth/readlogin`) @ApiParam({ name: 'Authorization', in: 'header', required: false, hidden: true }) async getOwnUserLoginInfo(@Headers("Authorization") authHeader: string) { // 业务逻辑 }
方法2:通过请求对象手动获取Token
既然已配置全局Swagger认证,可改用@Req()注入请求对象,从请求头中手动读取Authorization,避免Swagger自动生成多余参数:
import { Request } from 'express'; import { Req } from '@nestjs/common'; // ... @Get(`/v1/auth/readlogin`) async getOwnUserLoginInfo(@Req() req: Request) { const authHeader = req.headers.authorization; if (!authHeader) { throw new UnauthorizedException("No authorization header found"); } // 业务逻辑 }
补充:优化Swagger认证配置
当前addBearerAuth中的name字段设置为"JWT",与实际请求头Authorization不符,可调整为更规范的配置(不影响功能,但更贴合实际):
.addBearerAuth({ type: "http", scheme: "bearer", bearerFormat: "JWT", in: "header", name: "Authorization", // 修改为实际请求头名称 description: "Enter your Bearer token (格式: Bearer <token>)", }, "Authorization")
内容的提问来源于stack exchange,提问作者MattW
相关产品推荐
相关产品推荐

