Spring Boot Webflux - 安全 CORS 不起作用

标签 spring spring-boot spring-security spring-webflux

我似乎无法让 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

... o.s.w.c.reactive.DefaultCorsProcessor : Reject: headers '[authorization]' are not allowed

关于Spring Boot Webflux - 安全 CORS 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71362401/

相关文章:

java - Spring 作用域的问题

spring-boot - 配置 spring-devtools.properties 时,Spring Boot devtools Livereload 服务器未启动

java - 禁用/启用 OAuth2,无需两个安全配置

java - cvc-elt.1 : Cannot find the declaration of element 'beans'

java - 如何使 spring.profile.include 包含子文件夹中的 YAML 文件?

java - Spring云合约和webflux路由

java - 无法在 IntelliJ 中启动 Spring Boot +thymeleaf 应用程序

Spring OAuth2.0 - 动态注册OAuth2.0客户端

java - 如何修复在其主体中返回 null 的响应实体对象

java - 如何在 Spring-Integration 中将 SOAPAction header 添加到 HTTP 消息中?