带有POST请求的Spring Boot Security CORS

汤玛斯·希莉(TomášChylý):

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

当我将GET ajax请求发送到API时,它们可以正常工作。但是,当我发送POST请求时,我会因CORS错误而停止:

通过CORS策略已阻止从源“ http:// localhost:3000访问“ http:// localhost:8080 / item / add处的XMLHttpRequest :对预检请求的响应未通过访问控制检查:否'访问-Control-Allow-Origin'标头出现在请求的资源上。

我正在使用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还是很陌生,所以我确定我缺少一些东西。

汤玛斯·希莉(TomášChylý):

好的,当我重新阅读代码时,我发现了无法正常工作的原因。CMS中有一个错误而不是Spring Boot API。我使用了错误的API端点。因此,您不会收到404错误,而是CORS错误之一。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章