You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot集成SpringFox后Swagger UI授权按钮不显示问题

Swagger UI授权按钮不显示的解决方案

问题概述

Spring Boot应用中配置Swagger UI的JWT授权支持后,页面右上角未出现预期的“Authorize”按钮,无法输入JWT令牌到请求头中。

排查与修复步骤

1. 清理冗余依赖

你的build.gradle中重复引入了Swagger相关依赖,springfox-boot-starter:3.0.0已经包含springfox-swagger2和springfox-swagger-ui,重复依赖可能导致版本冲突或配置失效。修改依赖为:

implementation 'io.springfox:springfox-boot-starter:3.0.0'

2. 调整Swagger配置类

优化注解与规范(可选但推荐)

Springfox 3.x版本推荐使用@EnableOpenApi替代@EnableSwagger2,更好适配OpenAPI 3.0规范:

@Configuration
@EnableOpenApi // 替换原@EnableSwagger2
public class SwaggerConfig {
    
    @Bean
    public Docket apiDocket() {
        return new Docket(DocumentationType.OAS_30) // 对应OpenAPI 3.0规范
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                .paths(path -> !path.startsWith("/login"))
                .build()
                .securitySchemes(Arrays.asList(apiKey()))
                .securityContexts(Arrays.asList(securityContext()));
    }

    private ApiKey apiKey() {
        return new ApiKey("JWT", "Authorization", "header");
    }

    private SecurityContext securityContext() {
        // 指定需要应用授权的路径规则,确保Swagger识别到需授权的API
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .operationSelector(op -> op.requestMappingPattern().matches("/.*")) // 匹配所有API路径
                .build();
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Arrays.asList(new SecurityReference("JWT", authorizationScopes));
    }
}

若坚持使用Swagger 2.0规范,保留@EnableSwagger2和DocumentationType.SWAGGER_2,但必须确保securityContext中配置operationSelector——否则Swagger无法判定哪些API需要授权,不会显示按钮。

3. 验证配置生效

重启应用后访问Swagger UI(默认路径http://localhost:8080/swagger-ui/),检查右上角是否出现“Authorize”按钮。点击按钮后,输入Bearer {你的JWT令牌}格式的内容,即可自动将令牌添加到API请求的Authorization头中。


内容的提问来源于stack exchange,提问作者Deekshith M R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 16:53:25