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

Spring OAuth2集成Okta授权重定向后未存储JSESSIONID返回404问题

问题根因

你当前遇到的404错误是因为Spring Security默认没有接管/oauth2/redirect/okta这个回调路径,导致请求被路由到静态资源处理器,找不到对应资源返回404,只要显式指定OAuth2回调端点的匹配规则即可解决。

解决方案

1. 修改Security配置,显式指定重定向端点路径

在oauth2Login配置块下新增redirectionEndpoint配置,让Spring Security接管你自定义的回调路径前缀,修改后的配置如下:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/oauth_login", "/oauth2/**")
            .permitAll()
            .anyRequest().authenticated() // 建议补充该配置,其余接口需要登录后访问
            .and()
            .oauth2Login()
            .clientRegistrationRepository(clientRegRepo)
            .authorizedClientService(clientService)
            // 新增下面两行,指定回调路径的匹配规则,和你Okta配置的前缀保持一致
            .redirectionEndpoint()
            .baseUri("/oauth2/redirect/*");
}

2. 校验OAuth2客户端配置

确认你的ClientRegistration配置里,Okta对应的redirectUri值和Okta后台配置的回调地址完全一致,格式为{你的应用访问地址}/oauth2/redirect/okta。

3. 可选:Session配置调整(如果需要自定义JSESSIONID规则)

如果需要调整JSESSIONID的生成、过期策略,可以新增对应配置:

@Bean
public HttpSessionIdResolver httpSessionIdResolver() {
    // 默认就是Cookie存储JSESSIONID,需要自定义Cookie有效期、作用域等参数可以在这里调整
    return CookieHttpSessionIdResolver.defaultInstance();
}

// 也可以在HttpSecurity配置里补充Session规则
http.sessionManagement()
    .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
    .sessionFixation().migrateSession(); // 登录后保留原有session属性,为默认策略

配置完成后,Spring Security会自动处理Okta返回的授权码,完成身份认证后将用户信息存入SecurityContext,JSESSIONID也会正常写入客户端Cookie中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 13:45:02