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

Spring Session对接Keycloak时WebSession无复制行为问题咨询

故障根因

重定向循环的核心原因是Spring Security OAuth2 授权请求上下文未被正确序列化到Redis,仅存储在网关实例的本地内存中:

  • 单实例网关重启后本地内存清空,原有会话关联的state、nonce、code challenge等校验信息丢失,每次校验不通过都会触发重新授权,形成循环
  • 多实例部署时请求被负载均衡转发到未生成对应授权请求的实例,实例无法找到校验信息,直接返回302重定向到Keycloak登录页

修复方案

1. 配置Redis Session支持OAuth2类序列化

Spring Cloud Gateway基于WebFlux栈,默认的Spring Session Redis序列化配置未包含Spring Security OAuth2相关类的序列化规则,会导致授权请求无法持久化到Redis。添加以下配置自定义序列化器:

<!-- 新增Jackson JSR310时间类型序列化依赖,可选但推荐添加,避免时间序列化异常 -->
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.security.jackson2.SecurityJackson2Modules;

@Configuration
public class RedisSessionSerializationConfig {

    @Bean
    public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 注册Spring Security所有内置类的序列化规则,包含OAuth2相关类
        objectMapper.registerModules(SecurityJackson2Modules.getModules(getClass().getClassLoader()));
        // 开启多态类型序列化支持,避免反序列化时类型丢失
        objectMapper.activateDefaultTyping(
                ObjectMapper.DefaultTyping.NON_FINAL,
                JsonTypeInfo.As.PROPERTY
        );
        return new GenericJackson2JsonRedisSerializer(objectMapper);
    }
}

2. 确认授权请求存储实现正确

不要自定义替换默认的ServerOAuth2AuthorizationRequestRepository实现,Spring Security WebFlux默认的实现会自动将授权请求存储到当前会话中,只要会话对接了Redis就会自动同步到共享存储。

3. 多实例部署补充配置

确保所有网关实例的Session Cookie配置完全一致,避免Cookie不互通导致会话丢失:

server:
  reactive:
    session:
      cookie:
        domain: 你的业务域名
        path: /
        http-only: true
        secure: false # 生产环境使用HTTPS时改为true

验证方法

修复后完成登录,查看Redis中存储的Session内容,能找到org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest相关属性即为配置生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:30:01