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

Spring Boot集成Swagger UI时JWT授权头未携带问题排查

解决Swagger UI授权后请求头不带Authorization的问题

嘿,我太懂你这个困扰了!你已经配置了Swagger的SecurityScheme(也就是定义了JWT的认证方式),但还差关键的一步——告诉Swagger哪些请求需要自动带上这个授权头,也就是配置SecurityContexts。

问题根源

你只定义了“认证的方式是什么”,但没告诉Swagger“哪些请求要使用这个认证方式”,所以即使用户在UI里授权了,Swagger也不知道要把令牌放到请求头里。

修复后的完整配置

只需要在你的Docket配置里添加SecurityContext相关的配置即可,修改后的代码如下:

@EnableSwagger2 
@Configuration 
public class SwaggerConfig { 

    @Bean 
    public Docket api() { 
        List<SecurityScheme> schemeList = new ArrayList<>(); 
        schemeList.add(new ApiKey(HttpHeaders.AUTHORIZATION, "JWT", "header")); 

        return new Docket(DocumentationType.SWAGGER_2) 
                .produces(Collections.singleton("application/json")) 
                .consumes(Collections.singleton("application/json")) 
                .ignoredParameterTypes(Authentication.class) 
                .securitySchemes(schemeList)
                // 新增:关联安全上下文,指定哪些请求应用授权
                .securityContexts(Collections.singletonList(securityContext())) 
                .useDefaultResponseMessages(false) 
                .select() 
                .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot"))) 
                .paths(PathSelectors.any()) 
                .build(); 
    }

    // 定义安全上下文:指定哪些路径的请求需要携带授权头
    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                // 匹配所有API路径,你也可以根据需求改成特定路径
                .forPaths(PathSelectors.any())
                .build();
    }

    // 定义安全引用:把我们的JWT认证方案和授权范围绑定
    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "access所有API");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        // 这里的名字要和你定义的ApiKey名字一致(也就是HttpHeaders.AUTHORIZATION)
        return Collections.singletonList(
                new SecurityReference(HttpHeaders.AUTHORIZATION, authorizationScopes)
        );
    }
}

关键部分说明

  • securityContext():创建安全上下文,通过forPaths(PathSelectors.any())指定所有API请求都要应用这个授权规则,你也可以改成PathSelectors.ant("/api/**")这样的特定路径。
  • defaultAuth():将我们之前定义的ApiKey(标识为HttpHeaders.AUTHORIZATION)和一个全局授权范围绑定,让Swagger知道这个认证方案对应哪些API权限。

修改完之后重启你的服务,再次在Swagger UI里点击「授权」输入JWT令牌,发起请求时就能看到请求头里自动带上Authorization字段啦!

内容的提问来源于stack exchange,提问作者isADon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:00:51