Spring-Boot-Jersey Setup CORS
I fixed it this way,First create a class
public class CORSResponseFilter implements ContainerResponseFilter { public void filter(ContainerRequestContext requestContext,ContainerResponseContext responseContext) throws IOException { MultivaluedMap<String, Object> headers = responseContext.getHeaders(); headers.add("Access-Control-Allow-Origin", "*"); //headers.add("Access-Control-Allow-Origin", "http://abcd.org"); //allows CORS requests only coming from abcd.org headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); headers.add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia"); }}
The filter must inherit from the ContainerResponseFilter interface and must be registered as a provider:
public class JerseyConfig extends ResourceConfig { public JerseyConfig() { register(CORSResponseFilter.class); //other registrations }}
Fixed it by using the CORSFilter displayed in https://spring.io/blog/2015/01/20/the-resource-server-angular-js-and-spring-security-part-iii
@Component@Order(Ordered.HIGHEST_PRECEDENCE)class CorsFilter implements Filter { void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); response.setHeader("Access-Control-Max-Age", "3600"); if (request.getMethod()!='OPTIONS') { chain.doFilter(req, res); } else { } } void init(FilterConfig filterConfig) {} void destroy() {}}
Not sure if the @Provider annotation is supported by Spring. Try replacing the @Provider annotation with Springs @Component and the CORSFilter should extend org.springframework.web.filter.OncePerRequestFilter
. This is the Spring way of configuring Filters and this will work for any application server.
You can also configure CORS via the WebMvcConfigurerAdapter, which might be more compact:
@Beanpublic WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedHeaders("...") // add headers .allowedMethods(".."); // add methods } };}
Check out this guide!