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

Spring Boot 3.0.2下基于springdoc-openapi-starter-webmvc-ui启用Swagger OAuth2授权按钮

启用Swagger界面右上角OAuth 2.0授权按钮(Spring Boot 3.0.2 + springdoc-openapi)

你已经引入springdoc-openapi-starter-webmvc-ui依赖,只需通过配置OpenAPI的安全规则,就能启用Swagger UI的OAuth2授权按钮,具体步骤如下:

  • 添加OpenAPI配置类,定义OAuth2安全方案及授权流程:
    创建OpenApiConfig配置类,配置OAuth2的授权地址、Token地址、权限范围,并将安全规则绑定到OpenAPI实例中。示例代码如下:

    import io.swagger.v3.oas.models.OpenAPI;
    import io.swagger.v3.oas.models.info.Info;
    import io.swagger.v3.oas.models.security.OAuthFlow;
    import io.swagger.v3.oas.models.security.OAuthFlows;
    import io.swagger.v3.oas.models.security.Scopes;
    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() {
            // 定义API所需的OAuth2权限范围
            Scopes scopes = new Scopes()
                    .addString("read", "读取接口数据权限")
                    .addString("write", "修改接口数据权限");
    
            // 配置Authorization Code授权流程(根据你的实际授权模式调整)
            OAuthFlow authCodeFlow = new OAuthFlow()
                    .authorizationUrl("http://your-auth-server/oauth2/authorize") // 替换为你的授权服务器授权地址
                    .tokenUrl("http://your-auth-server/oauth2/token") // 替换为你的授权服务器Token获取地址
                    .scopes(scopes);
    
            OAuthFlows oAuthFlows = new OAuthFlows().authorizationCode(authCodeFlow);
    
            // 定义OAuth2安全方案
            SecurityScheme oAuth2Scheme = new SecurityScheme()
                    .type(SecurityScheme.Type.OAUTH2)
                    .flows(oAuthFlows)
                    .name("oauth2");
    
            // 为全局API添加安全要求
            SecurityRequirement securityReq = new SecurityRequirement().addList("oauth2");
    
            return new OpenAPI()
                    .info(new Info().title("系统API文档").version("v1.0"))
                    .addSecurityItem(securityReq)
                    .components(new io.swagger.v3.oas.models.Components()
                            .addSecuritySchemes("oauth2", oAuth2Scheme));
        }
    }
    
  • 适配你的授权模式:
    如果系统使用Password模式、Client Credentials模式等,只需修改OAuthFlows中的对应配置。比如Password模式示例:

    OAuthFlow passwordFlow = new OAuthFlow()
            .tokenUrl("http://your-auth-server/oauth2/token")
            .scopes(scopes);
    OAuthFlows oAuthFlows = new OAuthFlows().password(passwordFlow);
    
  • 注意事项:

    • 务必替换代码中的授权地址和Token地址为实际的OAuth2授权服务器地址
    • 确保Spring Boot项目已正确集成OAuth2资源服务器或客户端配置,Swagger UI的授权按钮仅提供前端交互入口,实际权限校验需后端配合完成

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 10:13:07