You need to enable JavaScript to run this app. 如何为Swagger OpenAPI 3.0配置授权以测试Keycloak保护的API
优惠活动
大模型
产品
解决方案
定价
更多

如何为Swagger OpenAPI 3.0配置授权以测试Keycloak保护的API

Springdoc OpenAPI 3.0 集成 Keycloak OAuth2 授权配置步骤

1. 修正依赖(可选)

你当前重复引入了两次springdoc-openapi-ui依赖,删除其中一个重复项即可,不影响现有功能运行。

2. 修改OpenAPI自定义配置Bean

在原有customOpenAPI Bean中添加OAuth2安全方案和安全上下文配置,示例代码如下:

import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.security.OAuthFlow;
import io.swagger.v3.oas.annotations.security.OAuthFlows;
import io.swagger.v3.oas.annotations.security.OAuthScope;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
// 定义OAuth2安全方案
@SecurityScheme(
    name = "keycloakOAuth2", // 安全方案名称,后续需要和安全要求的名称对应
    type = SecuritySchemeType.OAUTH2,
    flows = @OAuthFlows(
        authorizationCode = @OAuthFlow(
            authorizationUrl = "${keycloak.auth-server-url}/realms/${keycloak.realm}/protocol/openid-connect/auth",
            tokenUrl = "${keycloak.auth-server-url}/realms/${keycloak.realm}/protocol/openid-connect/token",
            scopes = {
                @OAuthScope(name = "openid", description = "OpenID scope"),
                @OAuthScope(name = "profile", description = "用户信息scope")
                // 按需添加你需要的其他scope
            }
        )
    )
)
public class OpenApiConfig {

    @Bean
    public OpenAPI customOpenAPI(@Value("${application-description}") String appDesciption,
                                 @Value("${application-version}") String appVersion) {
        // 如果你需要给所有接口全局添加安全要求,添加以下SecurityRequirement
        SecurityRequirement securityRequirement = new SecurityRequirement().addList("keycloakOAuth2");
        
        return new OpenAPI()
                .info(new Info().title("One Money Backend API")
                        .version(appVersion)
                        .description(appDesciption)
                        .termsOfService("http://swagger.io/terms/")
                        .license(new License().name("Apache 2.0").url("http://springdoc.org")))
                // 全局生效安全要求,不需要的话可以去掉,在单个接口单独配置
                .addSecurityItem(securityRequirement);
    }
}

如果不需要全局生效授权要求,可以删除上面的.addSecurityItem(securityRequirement)代码,在需要授权的接口类或者方法上添加@SecurityRequirement(name = "keycloakOAuth2")注解即可。

3. 添加Swagger UI OAuth2配置

在application.yml或application.properties中添加如下配置,替换为你自己的Keycloak客户端配置:

# Keycloak基础配置,替换为你自己的实际值
keycloak:
  auth-server-url: http://你的Keycloak地址/auth
  realm: 你的realm名称
  resource: 你的客户端ID

# Swagger UI OAuth2配置
springdoc:
  swagger-ui:
    oauth:
      client-id: ${keycloak.resource}
      # 如果你的Keycloak客户端是非公开类型,需要填写client-secret,公开客户端可以不填
      client-secret: 你的客户端密钥
      # 默认选中的scope
      scopes: openid,profile
      use-pkce-with-authorization-code-grant: true # 如果是公开客户端建议开启PKCE

4. Keycloak端配置

进入Keycloak管理后台,在你使用的客户端配置中,将http://你的应用地址/swagger-ui/oauth2-redirect.html添加到有效重定向URI列表中,保存配置。

5. 功能测试

启动应用后访问swagger-ui页面,点击页面右上角的Authorize按钮,找到你配置的keycloakOAuth2方案,勾选需要的scope后点击授权,会跳转到Keycloak登录页面,登录成功后即可直接在Swagger中调用受OAuth2保护的接口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 00:54:03