0

I have a Spring Boot application using version 2.7.6 and Kotlin. I have a frontend built with Angular and I'm trying to send requests to my backend. I use Spring Security in my project. I am having trouble setting a CORS configuration to allow my Angular frontend to send requests to the backend while developping both.

From my research online, it seems like I need a CORS configuration to allow the two to communicate while in development mode.

This is the CORS configuration I have added to my project:

@Configuration
@EnableWebMvc
class CorsConfig : WebMvcConfigurer {
    override fun addCorsMappings(registry: CorsRegistry) {
        registry.addMapping("/**")
    }
}

This is how I set up the CORS configuration in my WebSecurityConfig:

@EnableWebSecurity
@Configuration
class SecurityConfig @Autowired constructor(
    val authTokenFilter: AuthTokenFilter
){

    @Bean
    @Throws(Exception::class)
    fun filterChain(http: HttpSecurity): SecurityFilterChain? {
        http
            .httpBasic().disable()
            .csrf().disable()
            .cors()
                .and()
            .authorizeRequests()
                .anyRequest().permitAll()
                .and()
            .httpBasic()

        http
            .addFilterBefore(authTokenFilter, WebAsyncManagerIntegrationFilter::class.java)
        return http.build()
    }
}

I have tried using the @CrossOrigin annotation on the controller level like specified here but it doesn't seem to work either.

I have found this similar issue and the proposed solutions doesn't work either.

I have also tried both solutions provided by this answer to a similar issue but it still doesn't work.

My Spring Boot application doesn't log any error. The only thing I can see is in my developer tools on my navigator like so: enter image description here

The request passes through via Postman and it seems like I need to allow OPTIONS preflight. I have tried adding them to my SecurityConfig doing http.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll() but it doesn't work either.

Does anyone know what I'm doing wrong or how I should configure the CORS to be disabled throughout my application?

dur
  • 15,689
  • 25
  • 79
  • 125
  • @jub0bs I tried with the `cors()` call before the `authorizeRequests()` and it doesn't seem to be the root issue, I will keep it in that order from now on. – Hadestructhor Jan 13 '23 at 15:58
  • I see that the preflight response has status code 500. Do you know why? You need to fix that, because preflight responses must have a 2xx status code to succeed. – jub0bs Jan 13 '23 at 16:29
  • @Hadestructhor Are you sure that your `authTokenFilter` isn't throwing any exception? – dur Jan 15 '23 at 10:05
  • I have no stacktrace from my authTokenFilter – Hadestructhor Jan 16 '23 at 08:53

0 Answers0