
1. 为什么要在 Swagger 里配置全局 token做 Spring Boot 接口开发的同学大概率都遇到过这个场景项目集成了 JWT 或者自定义的 token 鉴权每次打开 Swagger UI 调试接口都要手动把 token 复制到请求头里。接口少的时候还能忍一旦有几十个接口每次调试都要重复粘贴效率低还容易出错。Swagger现在更多叫 OpenAPI本身提供了一个 Authorize 按钮机制只要在配置类里声明好 securityScheme就能在页面右上角出现一个授权入口填一次 token后续所有请求自动带上。这个能力在 springfox 和 springdoc 两套体系里都支持核心思路一致定义一个 SecurityScheme Bean把它注册到 Docket 或 OpenAPI 的 components 里再配合 SecurityContext 声明全局生效范围。这篇内容聚焦 Spring Boot 项目里通过 Bean 配置实现 Swagger 全局 token 的完整流程围绕 securityScheme、ApiKey 和 Bean 注入三个关键词展开。适合正在用 springfox 2.x/3.x 或者准备迁移到 springdoc 的后端开发也适合刚接触 Swagger 鉴权配置、想搞清楚 Authorize 按钮背后原理的同学。下面会给出可直接复制的 SwaggerConfig 骨架、securityScheme 配置片段以及启动后验证全局 token 是否生效的具体操作步骤。2. 前置准备依赖、版本与 TaoToken 接入在动手改配置之前先把环境理清楚。Swagger 的全局 token 配置在不同版本里 API 差异比较大选错版本会导致 Bean 注入报错或者 Authorize 按钮不出现。我这边常用的组合是 Spring Boot 2.7.x 搭配 springfox 3.0.0或者 Spring Boot 3.x 搭配 springdoc-openapi 2.x。两者的 securityScheme 写法不同下面会分别给出。如果你还在用 springfox 2.9.xApiKey 的构造参数顺序和 3.0 也有区别建议先确认版本。关于 token 的获取和调试如果你需要一套稳定的模型接口来做联调测试可以用 TaoToken 的 API 服务。它的接口地址是 https://taotoken.net/api 控制台里可以创建 API Keys配合模型对话页面能快速验证 token 是否可用。具体入口模型对话https://taotoken.net/models?utm_sourcetaotoken_aicg_blog_endutm_mediumcsdnutm_campaignrewriteutm_contentmodel_chatAPI Keys 管理https://taotoken.net/api-keys?utm_sourcetaotoken_aicg_blog_endutm_mediumcsdnutm_campaignrewriteutm_contentapi_keys接入文档https://taotoken.net/doc?utm_sourcetaotoken_aicg_blog_endutm_mediumcsdnutm_campaignrewriteutm_contentdoc拿到 key 之后你可以在 Swagger 的 Authorize 里填入验证全局 token 是否真的注入到了每个请求头。这一步很关键因为很多人配置完发现按钮出现了但请求还是 401问题往往出在 header 名称或者前缀上。3. 可复制配置SwaggerConfig Bean 骨架与 securityScheme3.1 springfox 3.0 的 SecurityScheme Bean 写法先看 springfox 体系。核心是定义一个返回 SecurityScheme 的 Bean然后在 Docket 里通过 securitySchemes 和 securityContext 注册。import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiKey; import springfox.documentation.service.AuthorizationScope; import springfox.documentation.service.SecurityReference; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; import java.util.Collections; import java.util.List; Configuration EnableSwagger2WebMvc public class SwaggerConfig { Bean public Docket apiDocket() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage(com.example.controller)) .paths(PathSelectors.any()) .build() .apiInfo(new ApiInfoBuilder().title(业务接口文档).version(1.0).build()) .securitySchemes(Collections.singletonList(securityScheme())) .securityContexts(Collections.singletonList(securityContext())); } Bean public SecurityScheme securityScheme() { return new ApiKey(token, token, header); } private SecurityContext securityContext() { return SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.regex(^(?!/(auth|login)).*$)) .build(); } private ListSecurityReference defaultAuth() { AuthorizationScope scope new AuthorizationScope(global, accessEverything); return Collections.singletonList(new SecurityReference(token, new AuthorizationScope[]{scope})); } }这里有几个点需要说明。new ApiKey(token, token, header)三个参数分别是securityScheme 的名称、实际请求头的 key、传递位置。第一个 token 是给 SecurityReference 引用的名字第二个 token 才是真正发到后端的 header 名。如果你后端用的是Authorization头就要改成new ApiKey(Authorization, Authorization, header)。forPaths里的正则用来排除登录、注册这类不需要 token 的接口避免在 Authorize 之前就被拦截。如果你希望所有接口都带 token可以直接用PathSelectors.any()。3.2 springdoc-openapi 的写法Spring Boot 3.x 项目大多用 springdoc配置方式换成 OpenAPI Beanimport io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.security.SecurityRequirement; import io.swagger.v3.oas.models.security.SecurityScheme; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; Configuration public class OpenApiConfig { private static final String SECURITY_SCHEME_NAME token; Bean public OpenAPI customOpenAPI() { return new OpenAPI() .info(new Info().title(业务接口文档).version(1.0)) .components(new Components() .addSecuritySchemes(SECURITY_SCHEME_NAME, new SecurityScheme() .name(SECURITY_SCHEME_NAME) .type(SecurityScheme.Type.APIKEY) .in(SecurityScheme.In.HEADER))) .addSecurityItem(new SecurityRequirement().addList(SECURITY_SCHEME_NAME)); } }springdoc 的SecurityScheme.Type.APIKEY对应 springfox 的 ApiKeyin(SecurityScheme.In.HEADER)表示放在请求头。addSecurityItem就是全局生效的关键它等价于 springfox 里的 securityContext。3.3 两种方案参数对照配置项springfox 3.0springdoc 2.x声明类型new ApiKey(name, key, header)SecurityScheme.Type.APIKEY注册位置Docket.securitySchemes()Components.addSecuritySchemes()全局生效SecurityContextSecurityReferenceaddSecurityItem(SecurityRequirement)排除路径forPaths(PathSelectors.regex(...))需在 SecurityRequirement 外单独处理注解开关EnableSwagger2WebMvc无需额外注解选哪套取决于你的 Spring Boot 版本。Boot 2.x 用 springfoxBoot 3.x 用 springdoc不要混用否则会出现 Bean 冲突或者页面 404。4. 验证请求Authorize 按钮与全局 token 生效配置写完之后启动项目访问 Swagger UI 地址。springfox 默认是http://localhost:8080/swagger-ui/index.htmlspringdoc 默认是http://localhost:8080/swagger-ui.html。页面加载后右上角会出现一个 Authorize 按钮。点击它会弹出一个输入框里面有一个名为 token 的字段。把你在 TaoToken 控制台创建的 API Key 粘贴进去点击 Authorize再点 Close。接下来随便找一个需要鉴权的接口点 Try it out填参数后 Execute。打开浏览器开发者工具的 Network 面板看这个请求的 Request Headers应该能看到token: 你的key这一行。如果看到了说明全局 token 已经生效后续所有接口都会自动带上这个头不用再手动粘贴。如果后端返回 401先检查 header 名称是否和后端过滤器里读取的一致。常见坑是 Swagger 里配了token后端却从Authorization里取两边对不上自然鉴权失败。另一个坑是 token 需要加Bearer前缀而 ApiKey 类型不会自动加这种情况要么改成 HTTP bearer 类型要么在输入时手动带上前缀。5. 本篇常见错排查Authorize 按钮不出现最常见的原因是 securityScheme Bean 没有被注册到 Docket 或 OpenAPI 里。检查securitySchemes()是否真的调用了以及 Bean 是否被 Spring 扫描到。如果配置类不在启动类的同级或子包下需要手动加ComponentScan。Bean 注入报错 NoSuchBeanDefinitionExceptionspringfox 和 springdoc 的类名冲突。比如同时引入了springfox-swagger2和springdoc-openapi-ui两个库都想注册 OpenAPI Bean启动就会失败。用mvn dependency:tree排查排除掉不需要的那个。请求头里没有 token先确认 Authorize 弹窗里点的是 Authorize 而不是 Cancel再确认接口路径没有被forPaths的正则排除掉。springdoc 没有 forPaths 的等价写法如果某个接口不需要 token得用Operation(security {})单独标注。token 过期后仍显示已授权Swagger UI 会把 token 存在浏览器本地过期后不会自动清除。点 Authorize 弹窗里的 Logout重新填入新 token 即可。这个行为在 springfox 和 springdoc 里都一样。跨域导致请求失败Swagger UI 和后端不同源时浏览器会拦截。后端加CrossOrigin或者全局 CORS 配置允许 Swagger 页面的来源。6. 长期编码与 Agent 场景的 token 管理如果你不只是调试单个接口而是在做长期的编码任务或者 Agent 编排token 的管理方式需要升级。手动在 Swagger 里粘贴 token 只适合临时调试真正跑自动化流程时token 应该由配置中心或者环境变量注入Swagger 的 Authorize 只是验证手段。对于需要长期调用模型接口做代码生成、Agent 编排的场景可以关注 TaoToken 的 Coding Plan它针对持续性的编码任务做了额度优化配合 API Keys 使用能减少频繁换 key 的麻烦。入口在这里Coding Planhttps://taotoken.net/coding-plan?utm_sourcetaotoken_aicg_blog_endutm_mediumcsdnutm_campaignrewriteutm_contentcoding_plan控制台https://taotoken.net/console?utm_sourcetaotoken_aicg_blog_endutm_mediumcsdnutm_campaignrewriteutm_contentconsole回到 Swagger 本身全局 token 配置的价值在于把鉴权这件事从每个接口的重复操作里抽出来变成一次配置、全局生效。springfox 用 SecurityScheme Bean 加 SecurityContextspringdoc 用 OpenAPI Bean 加 SecurityRequirement两套写法记住参数对照表就不会混。配完之后一定要用 Network 面板确认请求头真的带上了 token这一步比看页面按钮有没有出现更可靠。