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

Spring Boot 2 + OAuth2:授权码换令牌配置遇重定向循环求助

Spring Boot OAuth2 对接Okta出现重定向循环的解决办法

问题现象

配置Spring Boot OAuth2客户端对接Okta作为身份提供商(IdP)后,用户认证流程出现/login -> /authorize... -> /login... -> /login的无限重定向循环,Firefox提示服务器重定向请求无法完成。

你的配置信息

Okta端配置

登录重定向URI:http://localhost:8080/auth/login
登出重定向URI:http://localhost:8080/auth/logout
登录发起方:仅应用
发起登录URI:http://localhost:8080/auth/login

配置属性

okta:
  oauth2:
    client:
      client-id: clientId
      client-secret: clientSecret
      scope: openid profile email
      client-authentication-scheme: form
      access-token-uri: https://mydomain.oktapreview.com/oauth2/myapp/v1/token
      user-authorization-uri: https://mydomain.oktapreview.com/oauth2/myapp/v1/authorize
    resource:
      user-info-uri: https://mydomain.oktapreview.com/oauth2/myapp/v1/userinfo

过滤器代码

private Filter filter() {
  OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(
      "/login");
  OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(oktaClient(), oauth2ClientContext);
  filter.setRestTemplate(restTemplate);
  UserInfoTokenServices tokenServices = new UserInfoTokenServices(oktaResource().getUserInfoUri(),
      oktaClient().getClientId());
  tokenServices.setRestTemplate(restTemplate);
  filter.setTokenServices(tokenServices);

  return filter;
}

WebSecurity配置

@Configuration
@EnableOAuth2Client
public class WebSecConfig extends WebSecurityConfigurerAdapter {
....
@Override
public void configure(HttpSecurity http) throws Exception {
  http.antMatcher("/**").authorizeRequests()
      .antMatchers("/", "/login**", "/logout**", "/v2/api-docs", "/configuration/ui",
          "/configuration/security", "/swagger-resources/**", "/swagger-ui.html", "/webjars/**")
      .permitAll()
      .anyRequest().authenticated().and().exceptionHandling()
      .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")).and().csrf()
      .csrfTokenRepository(
          CookieCsrfTokenRepository.withHttpOnlyFalse()).and().addFilterBefore(filter(),
      BasicAuthenticationFilter.class);
}
....
}

问题分析

这个重定向循环的核心诱因是:
你的LoginUrlAuthenticationEntryPoint设置为/login,而OAuth2的认证过滤器也绑定在/login路径。当Okta认证完成后携带授权码(code)重定向回/login时,过滤器处理完认证逻辑后,系统可能因为未正确识别已认证状态,再次触发LoginUrlAuthenticationEntryPoint的跳转逻辑,最终形成无限循环。

解决方案

你已经验证有效的解决方式:

  1. 调整认证入口跳转路径:将LoginUrlAuthenticationEntryPoint("/login")修改为LoginUrlAuthenticationEntryPoint("/")
    • 未认证请求会跳转到允许匿名访问的根路径,不会触发重复的认证跳转;同时OAuth2过滤器依然能正常处理/login路径的回调逻辑,完成用户身份认证。
  2. 重新创建Okta授权服务器:确保授权服务器的配置与Spring Boot客户端的配置完全匹配,避免因配置不一致导致的认证状态识别异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:15:09