Home > Back-end >  CORS header ‘Access-Control-Allow-Origin’ missing with Spring Data REST
CORS header ‘Access-Control-Allow-Origin’ missing with Spring Data REST

Time:09-17

I'm trying to solve a CORS issue with spring data rest but seems like the CORS headers are not attached. This is the config I have:

@Component
class DataRestConfig: RepositoryRestConfigurer {
    override fun configureRepositoryRestConfiguration(config: RepositoryRestConfiguration?, cors: CorsRegistry?) {
        cors?.addMapping("/*")
           ?.allowedOrigins("*")
           ?.allowedMethods("GET", "PUT", "DELETE","PATCH","POST","OPTIONS")
     }
}

I also had the same issue with other API routes that are out of spring data rest. Here is my WebSecurityConfigurerAdapter's configure

override fun configure(http: HttpSecurity) {
    http
        .cors().and()
        .csrf().disable()
        .addFilterAfter(JWTAuthorizationFilter(userDetailsServices, secret, jwtService),UsernamePasswordAuthenticationFilter::class.java)
        .authorizeRequests()
        .antMatchers(HttpMethod.POST,UserController.LOGIN_URL).permitAll()
        .anyRequest().authenticated()
}

CodePudding user response:

If using Spring MVC you should configure the CORS behavior like so

@Configuration
public class CorsConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOrigins("http://localhost:3000")
            .allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS");
    }
}

CodePudding user response:

You can always have a CorsFilter to modify response headers. Here I have answered how we can have custom CorsFilter in Spring boot - https://stackoverflow.com/a/66882700/3709922. Kindly have a look.

  • Related