I serve my front- and backend from two different servers. Now I am trying to get CORS working on the Spring-Boot-Jersey backend. I tried everything I could find on the internet but nothing seem to work or I am missing something.
My current setup uses a ContainerResponseFilter
. I tried registering it automatically with @Provider
and manually in the Jersey configuration.
ContainerResponseFilter
@Provider
public class CORSFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext request,
ContainerResponseContext response) throws IOException {
response.getHeaders().add("Access-Control-Allow-Origin", "*");
response.getHeaders().add("Access-Control-Allow-Headers",
"origin, content-type, accept, authorization");
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS, HEAD");
}
}
Maybe it is important but I also used Spring-Security-oauth2
by adding the @EnableOAuth2Sso
annotation. Please tell me if you need more of my setup.
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() {}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With