我似乎无法让 CORS 在 Spring Boot 的 Webflux 中正常工作 - 这是我的配置,无论我做什么,我都会在 VUE 客户端中遇到 CORS 错误:
@Configuration
@EnableWebFluxSecurity
class HelloWebfluxSecurityConfig {
@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
val configuration = CorsConfiguration()
configuration.allowedOrigins = listOf("http://localhost:8080")
configuration.allowedMethods = listOf("GET", "POST", "PUT", "DELETE", "OPTIONS")
val source = UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration("/**", configuration)
return source
}
@Bean
fun userDetailsService(): MapReactiveUserDetailsService {
val user: UserDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("user")
.roles("USER")
.build()
return MapReactiveUserDetailsService(user)
}
@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
http
.authorizeExchange { exchanges: AuthorizeExchangeSpec ->
exchanges
.anyExchange().authenticated()
}
.httpBasic(withDefaults())
.formLogin(withDefaults())
.csrf().disable()
.cors().configurationSource(corsConfigurationSource())
return http.build()
}
}
我也尝试过 cors().configurationSource(withDefaults())
(根据文档,它应该使用我定义的配置源 bean。
我需要做什么才能使这项工作成功?
编辑:这是我的浏览器错误:
Access to XMLHttpRequest at 'http://localhost:8088/data/configuration' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
最佳答案
所以,事实证明我需要添加:
configuration.allowedHeaders = listOf("*")
任何遇到此问题的人都可以将其添加到 application.properties
查看请求被拒绝的确切原因(或将调试器设置为在 DefaultCorsProcessor
类中进行调试)并观察会发生什么:
logging.level.org.springframework.web.cors.reactive.DefaultCorsProcessor=debug
block 引用>... o.s.w.c.reactive.DefaultCorsProcessor : Reject: headers '[authorization]' are not allowed
关于Spring Boot Webflux - 安全 CORS 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71362401/