Saturday 10 September 2022

Enabling Cross Origin Requests for a RESTful Web Service
How to Resolve Cross Origin Error in Java Spring Application




This Cross Origin Error Occurs then you are trying to access your Spring boot or Spring Application from outer source. Like Angular, React and other ways.
you can resolve this Error by creating A Cross CORSFilter or you can create simpleCorsFilter Bean in Configuration class

------------------------------------------- CORSFilter ----------------------------------------------------------

import javax.servlet.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
 
 @Component
  public class CORSFilter implements Filter {
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException{
  HttpServletResponse response = (HttpServletResponse) res;
  response.setHeader("Access-Control-Allow-Origin", "*");
  response.setHeader("Access-Control-Allow-Methods", "POST, GET");
  response.setHeader("Access-Control-Max-Age", "3700");
  response.setHeader("Access-Control-Allow-Headers","Content-Type");
  response.setHeader("Access-Control-Allow-Credentials","true");
  chain.doFilter(req, res);
  }
  public void init(FilterConfig filterConfig) {
  }
  public void destroy() {
  }
  }

------------------------------------------------------ simpleCorsFilter  Bean -------------------------------------

@Bean
public FilterRegistrationBean simpleCorsFilter() {  
   UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();  
   CorsConfiguration config = new CorsConfiguration();  
   config.setAllowCredentials(true);
   // *** URL below needs to match the Vue client URL and port ***
   config.setAllowedOrigins(Collections.singletonList("https://192.168.1.204:4200"));
   config.setAllowedMethods(Collections.singletonList("*"));  
   config.setAllowedHeaders(Collections.singletonList("*"));  
   source.registerCorsConfiguration("/**", config);
   
   FilterRegistrationBean bean = new FilterRegistrationBean<>(new CorsFilter(source));
   bean.setOrder(Ordered.HIGHEST_PRECEDENCE);  
   return bean;  
}  


No comments:

Post a Comment