Spring Boot Data Rest + CORS not being enabled properly for OPTIONS/DELETE

后端 未结 4 1027
暖寄归人
暖寄归人 2020-12-21 07:08

I\'ve got an extremely simple example that I can\'t get to work.

I have my domain that models my database, and my Repository.

public interface MyTes         


        
4条回答
  •  Happy的楠姐
    2020-12-21 07:34

    The following configuration works for me in a Spring Data Rest based application. The important point to note is that the filter is registered to execute before the Security Filter chain kicks in.

    @Configuration
    @EnableWebSecurity
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter
    {
      @Override
      public void configure(HttpSecurity http) throws Exception
      {
        http.addFilterBefore(corsFilter(), ChannelProcessingFilter.class);
      }
    
      @Bean
      protected Filter corsFilter()
      {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        config.addExposedHeader("Location");
    
        source.registerCorsConfiguration("/**", config);
    
        return new CorsFilter(source);
      }
    }
    

提交回复
热议问题