【问题标题】:Spring Boot Security CORS with POST request带有 POST 请求的 Spring Boot Security CORS
【发布时间】:2019-12-26 00:33:24
【问题描述】:

我有 Spring Boot REST API 和基于 React 的 CMS。

当我向 API 发送 GET ajax 请求时,它们工作正常。但是当我发送 POST 请求时,我被 CORS 错误阻止:

从源“http://localhost:3000”访问“http://localhost:8080/item/add”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“访问控制允许源” ' 请求的资源上存在标头。

我正在使用 WebSecurityConfigurerAdapter 来配置安全性。

BasicWebSecurityConfigurerAdapter.kt

override fun configure(http: HttpSecurity?) {
    http?.csrf()?.disable()
    http?.cors()
    http?.authorizeRequests()
            ?.anyRequest()?.authenticated()
            ?.and()
            ?.httpBasic()
}

@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
    val configuration = CorsConfiguration()
    configuration.allowedOrigins = mutableListOf("http://localhost:3000")
    configuration.allowedMethods = mutableListOf("GET", "POST")

    val source = UrlBasedCorsConfigurationSource()
    source.registerCorsConfiguration("/**", configuration)

    return source
}

我也尝试在我的 RestControllers 上使用注释,但我遇到了同样的问题,GET 请求有效而 POST 请求无效。 我对 Spring Boot 还很陌生,所以我确信我缺少一些东西。

【问题讨论】:

  • 我的控制器方法顶部的 @CrossOrigin 等注释非常适合我。
  • 正如我在问题中所写,我使用它们得到了相同的结果。在尝试使用 WebSecurityConfigurerAdapter 之前,我先尝试了注释。
  • 以防万一,你用的是什么spring boot版本?我正在使用 2.1.4.RELEASE。您还可以提供更多代码吗?将尝试在本地复制它。
  • Spring Boot 是 2.1.6.RELEASE,我会用更多代码更新问题。
  • 谢谢 :) 当我要更新问题时,我重新阅读了代码并能够找到错误,它完全在其他地方。

标签: spring spring-boot kotlin spring-security


【解决方案1】:

好的,当我重新阅读代码时,我发现了这个不起作用的原因。 CMS 中存在错误,而不是 Spring Boot API。我使用了错误的 API 端点。 所以你不会得到 404 错误,而是 CORS 一个。

但是,由于某种原因,CORS 无法使用 WebSecurityConfigurerAdapter 工作。 相反,我已经回到在控制器上使用注释 @CrossOrigin。

【讨论】:

    猜你喜欢
    • 2018-03-06
    • 2020-12-29
    • 1970-01-01
    • 2021-02-10
    • 2020-06-11
    • 2019-07-16
    • 2015-11-15
    • 2016-01-08
    相关资源
    最近更新 更多