简体   繁体   中英

Spring-Boot-Jersey Setup CORS

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() {}

}

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:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedHeaders("...") // add headers
                    .allowedMethods(".."); // add methods
        }
    };
}

Check out this guide!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM