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

Spring Cloud Gateway整合Keycloak OAuth2启动报MvcFoundOnClasspathException问询

错误根因

Spring Cloud Gateway 基于 Spring WebFlux 响应式框架开发,官方明确禁止类路径中存在 Spring MVC(spring-webmvc)相关依赖,否则启动就会抛出MvcFoundOnClasspathException异常。你引入的默认 Keycloak 客户端适配的是 Spring MVC 架构,自动传递了spring-webmvc依赖,所以触发了类路径校验失败。

解决方案

方案一:使用Spring Security官方OAuth2客户端集成(推荐)

Keycloak官方自2022年起已废弃自有的Spring客户端适配器,推荐使用Spring Security原生OAuth2能力对接,天然兼容Spring Cloud Gateway的WebFlux架构,不会引入MVC依赖:

  1. 调整依赖(以Maven为例,Gradle对应修改即可),移除原有Keycloak starter依赖,引入以下依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
  1. 替换原有Keycloak配置,修改application.yml为Spring Security OAuth2标准配置格式:
spring:
  security:
    oauth2:
      client:
        provider:
          keycloak:
            issuer-uri: http://localhost:8083/auth/realms/xxx
            user-name-attribute: preferred_username
        registration:
          keycloak:
            client-id: login-app
            authorization-grant-type: authorization_code
            scope: openid
  cloud:
    gateway:
      routes:
        - id: my_route
          uri: http://MyLegacyServer:8080
          predicates:
            - Path=/**
  1. 添加WebFlux安全配置类,开启网关的OAuth2登录校验:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        http
            .authorizeExchange(exchanges -> exchanges
                .anyExchange().authenticated()
            )
            .oauth2Login(oauth2Login -> {});
        return http.build();
    }
}

方案二:适配原有Keycloak配置(不推荐,仅兼容旧代码)

如果必须使用原有Keycloak适配器,需要手动调整依赖:

  • 在Keycloak依赖的声明中排除spring-webmvc、spring-boot-starter-web等MVC相关传递依赖
  • 额外引入Keycloak WebFlux适配依赖keycloak-spring-security-adapter,配合WebFlux安全规则配置使用
    该方案兼容性较差,新版本Keycloak已停止维护适配器,仅作为临时兼容方案使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:09:04