2

I implemented rest web services with Spring. When I deployed it in Eclipse as a Spring Boot Application, it works. However when I deployed it in Tomcat 7 on the same machine, it does not work. The error message is as follows:

XMLHttpRequest cannot load http://localhost:8080/ristoreService/oauth/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8081' is therefore not allowed access.

My CORS filter looks like this:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8081");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me, "
                + "Origin,Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

If I comment out response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8081");, I still get the same error. It wouldn't work without this line even if I deploy in Eclipse. Why does it act differently being deployed under different environment on the same ip?

EDIT: I tested the url http://localhost:8080/ristoreService/oauth/tokenwith rest client tester "CocoaRestClient" and got 404. So I made up a url which apparently does not exist http://localhost:8080/xxxxx and run it in UI (angularjs) and again got the CORS error. I think the error is kind of misleading, it is after all a 404. But why does it complain not found when the war was deployed successfully with the name ristoreService.war under webapps in Tomcat?

ddd
  • 4,665
  • 14
  • 69
  • 125
  • related: http://stackoverflow.com/questions/1653308/access-control-allow-origin-multiple-origin-domains – Kadima Aug 04 '16 at 18:24
  • @Ulises Mentioned in my post `Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8081' is therefore not allowed access.` – ddd Aug 04 '16 at 18:34

3 Answers3

1

Try using a FilterRegistrationBean. Looks like this in Java Config:

@Bean
public FilterRegistrationBean authorizationFilter(){
    FilterRegistrationBean filterRegBean = new FilterRegistrationBean();
    filterRegBean.setFilter(authorizationFilter);
    List<String> urlPatterns = new ArrayList<String>();
    urlPatterns.add("/v1/*");
    filterRegBean.setUrlPatterns(urlPatterns);
    return filterRegBean;
}

Any reason why you're not using Spring Boot's CORS capabilities? It's already supported out of the box, you just gotta configure it. You can enable it globally like this:

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*");
            }
        };
    }
Ulises
  • 9,115
  • 2
  • 30
  • 27
  • Spring Boot's own corsConfigurer should work the same as the CORSFilter I had, right? I added CorsMapping in my Application and still got the same error. Just realize this error may not be what it means. Since I tested the same url in a rest client tester and got 404. It may not be a CORS issue after all. But why 404? – ddd Aug 04 '16 at 19:44
  • You probably aren't setting the right context path in tomcat. How are you configuring tomcat? – Ulises Aug 04 '16 at 19:52
  • I didn't do any config for context path. Everything is default. – ddd Aug 04 '16 at 20:02
  • Where is this coming from? ristoreService – Ulises Aug 04 '16 at 20:09
  • What do you mean? The web service I created was deployed with the name ristoreSerivice.war. I copied the war to webapps dir under tomcat. I don't have a `web.xml`. Could it be the cause? – ddd Aug 04 '16 at 20:10
0

According to How to deploy Spring Boot application, I have to make main application to extend SpringBootServletInitializer. Once I added that, it works.

ddd
  • 4,665
  • 14
  • 69
  • 125
0

To solve CORS issue I used @CrossOrigin. And I did not implement my own CORS filter. Any way spring already have provided few addition solutions for CORS issue.

If you need only your filter you could use it in this way:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.addFilterBefore(yourFilter);
    ...
}
Sergii
  • 7,044
  • 14
  • 58
  • 116