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

Keycloak集成Spring Boot实现Google社交登录出现重定向次数过多报错

问题根因

产生重定向循环的核心原因有2个:

  1. 你配置的回调地址/test/redirect未加入Spring Security的白名单,Keycloak完成谷歌认证回调到该地址时,Spring Security检测到请求未认证,会302重定向到Keycloak登录端点/sso/login,而适配器处理登录逻辑后又会跳回回调地址,形成无限循环。
  2. 你自定义了授权链接的回调地址为/test/redirect,但Keycloak Spring Security适配器默认只处理发往/sso/login端点的认证回调请求,不会自动处理你自定义回调地址携带的code参数,无法完成用户登录态的创建,进一步加剧了循环。

修复方案

  • 第一步:修正Spring Security配置

    在KeyCloakConfig的configure方法中,把/sso/login和/test/redirect都加入白名单:
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.authorizeRequests()
                .antMatchers("/test/unprotected-data").permitAll()
                .antMatchers("/test/generator").permitAll()
                .antMatchers("/sso/login").permitAll()
                .antMatchers("/test/redirect").permitAll()
                .anyRequest().authenticated();
    }
    
  • 第二步:修正授权链接的回调地址(二选一即可)

    方案A(推荐,使用适配器默认逻辑):把brokerGenerator方法中的redirectUri修改为Keycloak适配器默认的回调端点:
    String redirectUri = "http://localhost:8081/sso/login";
    
    适配器会自动用返回的code换取accessToken、refreshToken,完成用户身份认证并创建登录态,你可以额外配置登录成功后的默认跳转地址到你的业务页面。
    方案B(保留自定义回调):如果你需要自己处理回调逻辑,需要在/test/redirect接口中手动实现code换token、token校验、Spring Security上下文写入的逻辑,避免后续访问受保护接口时再次触发重定向。
  • 第三步:检查配置合法性

    1. 确保你的application.properties/application.yml中已经正确配置Keycloak客户端参数,如果你使用的是confidential类型的客户端,必须配置client-secret:
    keycloak.realm=keycloak-lerning-realm
    keycloak.auth-server-url=http://localhost:8080/auth
    keycloak.resource=keycloak-lerning-server
    keycloak.credentials.secret=你的Keycloak客户端密钥
    keycloak.use-resource-role-mappings=true
    
    1. 确认你在Keycloak控制台的客户端配置中,已经把用到的重定向地址(http://localhost:8081/*)加入到「有效重定向URI」列表中,避免Keycloak侧拦截回调请求。

完成以上修改后重启服务,重新生成授权链接进行登录测试即可解决重定向循环问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:48:02