Implement CORS Filter Using Springboot

Springboot CORS implementatin in Application.java Add below piece of code in your Application.java of your spring boot project


 import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter;

 @Bean
 public FilterRegistrationBean corsFilter()
 {

 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();      CorsConfiguration config = new CorsConfiguration();
 config.setAllowCredentials(true);
 config.addAllowedOrigin("*");
 config.addAllowedHeader("Content-Type");
 config.addAllowedMethod("OPTIONS");
 config.addAllowedMethod("GET");
 config.addAllowedMethod("PUT");
 config.addAllowedMethod("POST");
 config.addAllowedMethod("DELETE");
 source.registerCorsConfiguration("/**", config);
 FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));  bean.setOrder(0);
 return bean;

 }

0 comments:

Post a Comment