如何在OpenAPI 3.1.0 UI中隐藏必填Authorization请求头
你的问题根源是重复配置了认证逻辑:既通过security字段启用了bearerAuth安全方案,又手动添加了Authorization请求头参数,导致Swagger UI同时显示两个需要填写的Authorization相关输入项。按以下方式修改即可解决:
1. 移除手动定义的Authorization请求头参数
不管是OpenAPI Schema还是Fastify路由配置里,都要删掉手动添加的Authorization头参数——security: [{ bearerAuth: [] }]的配置已经会让Swagger UI自动生成对应的认证入口,完全不需要重复定义请求头。
修改后的OpenAPI Schema示例
openapi: 3.1.0 info: title: Test version: 1.0.0 components: securitySchemes: bearerAuth: type: http scheme: bearer schemas: {} paths: /user: post: requestBody: content: application/json: schema: type: object properties: name: type: string required: true # 移除手动添加的authorization请求头参数 security: - bearerAuth: [] responses: "200": description: Default Response
修改后的Fastify配置代码
import { fastify } from "fastify"; import fs from "@fastify/swagger"; import fsu from "@fastify/swagger-ui"; const app = fastify(); await app.register(fs, { openapi: { openapi: "3.1.0", components: { securitySchemes: { bearerAuth: { type: "http", scheme: "bearer", }, }, }, security: [{ bearerAuth: [] }], }, }); // 可选:配置Swagger UI自动携带测试token,避免每次手动输入 await app.register(fsu, { uiConfig: { requestInterceptor: (req) => { // 替换成你的测试用token,留空则需用户点击顶部「Authorize」按钮输入一次 req.headers.Authorization = "Bearer your-test-token"; return req; }, }, }); app.get( "/", { schema: { // 移除手动定义的authorization头配置 }, }, async (request, reply) => { return { hello: "world" }; } ); app .listen({ port: 3001 }) .then(() => { console.log("listening"); }) .catch((err) => console.log(err));
效果说明
- 移除手动头参数后,Swagger UI只会显示顶部的「Authorize」按钮,点击输入一次bearer token即可全局生效,不会在每个接口的请求区域重复显示Authorization输入框。
- 若配置了
requestInterceptor,UI会自动给所有请求带上预设的token,彻底省去手动输入步骤。
内容的提问来源于stack exchange,提问作者Nick Berilov
相关产品推荐
相关产品推荐

