首页 > 解决方案 > 反应被重定向到登录页面时出现 CORS 错误

问题描述

我收到以下错误消息:-由于访问控制检查,Fetch API 无法加载 http://localhost:8080/oauth2/authorization/google -加载资源失败:跨域重定向到 https://accounts.google。 .. 被 CORS 政策拒绝:Access-Control-Allow-Origin 不允许 Origin http://localhost:3000

我制作了一个 Kotlin-SpringBoot API,并且正在使用 React-TypeScript 开发前端。我使用 SwaggerCodegen 导入函数以与我的 API 与 OpenAPI 文档进行交互。

我希望我的用户通过 google OAUTH 进行身份验证,因此我决定使用 Spring Security 使我的所有端点都需要身份验证。我使用这个类做到了:

@Configuration
class SecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http
                .antMatcher("/**").authorizeRequests()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
                .oauth2Login()

    }
}

现在,api 在端口 8080 上,前端在 3000 上,所以如果我访问 localhost:8080/restricted,我会收到登录提示,它可以按预期工作。但是,如果我在 localhost:3000 上的前端尝试从 API 中检索任何数据,我认为它只会重定向我,但我得到了上面的 CORS 错误。我到处寻找,只想知道我的方法是否在概念上是错误的,或者我如何授权这种类型的重定向(或者我什至应该)。

谢谢你的帮助!

标签: reactjsspringspring-bootspring-securityswagger

解决方案


推荐阅读