Spring Config To Disable CORS Issue In Spring Boot

Spring Config To Disable CORS Issue In Spring Boot

We face  CORS(Cross-origin resource sharing) issue specially when  working with react or angular apps and running spring boot on different port, and front end app on some other to solve the CORS issue in spring boot is very easy and simple. to know Solve the issue we should know the cause.

So when we are working front end trying to call a service on back end which are running on different domain or ports during development,browser  as security measure calls an Pre-flight request as option method seeking permission to access the required service with allowed headers and method  to perform an actual request, by default the option method will be disabled, in some cases certain methods or headers are restricted. we need to override options to provide 200 as response granting the permission.

So lets Enable CORS  in the spring boot application running on embedded tomcat. the configuration is pretty simple and straight forward.

Create an class in spring boot Application with following code to Enable CORS(Cross-origin resource sharing) in spring boot application.

package <..........>;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CORSAdvice {

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }

}

So after writing this class rebuild the spring boot application and happy coding..!!!