Home > OS >  Spring Boot Webflux - Security CORS is not working
Spring Boot Webflux - Security CORS is not working

Time:03-06

I cannot seem to get CORS working right in Spring Boot's Webflux - here is my config and no matter what I do I get CORS errors with a VUE client:

@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()
    }
}

I've tried cors().configurationSource(withDefaults()) too (which should use the configuration source bean I've defined, according to the docs.

What do I need to do to make this work?

EDIT: Here's my browser error:

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.

CodePudding user response:

So, it turns out that I needed to add:

configuration.allowedHeaders = listOf("*")

Anybody that's having problems with this can add this to application.properties to see the exact reason that the request is rejected (or set your debugger to debug in the DefaultCorsProcessor class and watch what happens:

logging.level.org.springframework.web.cors.reactive.DefaultCorsProcessor=debug

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

CodePudding user response:

In Rest controller you could do this:

@RestController
@CrossOrigin(origins = "*")

for webflux look at this: Enable CORS in Spring 5 Webflux?

  • Related