首页 > 解决方案 > 302 Okta 重定向 - CORS 问题

问题描述

我有一个配置为使用 Okta 作为 SP 发起的 SSO 的 Spring Boot 应用程序,我已将 Okta 开发人员帐户配置为使用“OIDC - OpenID Connect”和“Web 应用程序”作为应用程序类型。
在此处输入图像描述

当我从浏览器访问 SP 端点时,访问 Okta 的登录页面没有问题 例如:http://localhost:8080/api/login

但是,当我从我的 React 应用程序调用 API 端点时,它会因 CORS 问题而失败

axios({
    method: 'GET',
    url: 'http://localhost:8080/api/login',
    withCredentials: true
})
.then(response => {
    if (response.data.userID)
    {
        console.log("UserId:" + response.data.userID);
    }
})
.catch(error => {
    console.error(error);
})

以下是重定向到 Okta(302) 的标头信息似乎是问题所在: 在此处输入图像描述

我在 Okta 管理控制台中更新了 react 应用程序的 url 可信来源

在此处输入图像描述

以下是 Okta 的登录重定向 uri

Okta 登录 URI

这是我的弹簧启动配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableOAuth2Sso
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
        configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
    @Override
    public void configure(WebSecurity webSecurity) throws Exception {
        webSecurity
                .ignoring()
                .antMatchers(HttpMethod.OPTIONS, "/**")
                .and()
                .ignoring();
    }
    
}

任何想法?我在这里想念什么?

标签: reactjsspring-bootcorsopenid-connectokta

解决方案


您对使用过的技术使用了错误的流程。在应用程序类型中也提到了它: 在此处输入图像描述

使用正确的流程 -Authorization Code Flow with Proof Key for Code Exchange (PKCE)对于 React 应用程序(本机应用程序),您不会遇到 CORS 问题。或者将您的前端编写为服务器端应用程序而不是 SPA (React)。


推荐阅读