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

Spring Boot 3.0.0项目中配置Swagger的Bearer Token授权按钮

Spring Boot 3.0.0项目中配置Swagger的Bearer Token授权按钮

嘿,我完全懂你想要的效果——就是在Swagger界面上添加一个能输入Bearer Token的授权按钮对吧?确实,Spring Boot 3.x版本用的是SpringDoc OpenAPI(替代了旧版的Springfox Swagger),旧配置确实不适用了,我给你一步步讲怎么配置:

1. 添加SpringDoc OpenAPI依赖

首先得把正确的依赖加到项目里,Spring Boot 3对应的是springdoc-openapi-starter-webmvc-ui:

Maven(pom.xml)

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.2.0</version> <!-- 可以替换为最新稳定版 -->
</dependency>

Gradle(build.gradle)

implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'

2. 创建OpenAPI配置类

接下来写一个配置类,定义Bearer Token的安全方案,这样Swagger UI就会自动生成授权按钮:

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
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 {

    @Bean
    public OpenAPI customOpenAPI() {
        // 定义安全方案的名称,后续会引用它
        final String securitySchemeName = "bearerAuth";
        
        return new OpenAPI()
                // 全局启用这个授权方案,所有接口默认会自动带上授权Header
                .addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
                .components(
                        new Components()
                                .addSecuritySchemes(securitySchemeName,
                                        new SecurityScheme()
                                                .name(securitySchemeName)
                                                .type(SecurityScheme.Type.HTTP) // 认证类型为HTTP
                                                .scheme("bearer") // 指定为Bearer认证方案
                                                .bearerFormat("JWT") // 可选,提示Token格式为JWT,界面会显示说明
                                                .in(SecurityScheme.In.HEADER) // Token放在请求Header中传递
                                )
                );
    }
}

3. 测试授权按钮

启动你的Spring Boot项目,访问Swagger UI地址:http://localhost:8080/swagger-ui.html(如果项目端口不是8080,替换成你实际的端口)。

你会看到界面右上角多了一个Authorize按钮,点击它会弹出输入框,直接填入你的Bearer Token就行(不需要加Bearer 前缀,配置里已经指定了scheme,界面会自动处理),点击Authorize完成授权。之后所有接口请求都会自动带上Authorization: Bearer {你的Token}这个Header啦!

额外小提示

  • 如果你的项目是WebFlux类型,依赖要换成springdoc-openapi-starter-webflux-ui
  • 要是不想全局启用授权,可以去掉.addSecurityItem(...)这一行,然后在需要授权的接口/控制器上添加@SecurityRequirement(name = "bearerAuth")注解来单独启用
  • 想修改Swagger UI的标题、描述等信息,可以在customOpenAPI()里链式调用.info(new Info().title("你的API文档").version("v1").description("API功能描述"))

备注:内容来源于stack exchange,提问作者 Anil Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 12:09:57