Shawn Zhou
Shawn Zhou

Reputation: 89

Enable CORS on Tomcat 8.0.30

Appreciate any help.

I'm facing the problem with the CORS on my newly deployed Tomcat 8.0.30. I keep getting the error below. I am using 127.0.0.1 as the API server address and 192.168.1.100 is the address of my HTTP server.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '_http://192.168.1.100:8999' is therefore not allowed access. The response had HTTP status code 403.

Read through whole Tomcat documentation, added the cors filter under the tomcat web.xml, as well as the project web.xml, but nothing magic happens here, still getting the same error. Tried both minimal and advanced with init-param, same error.

I am using Spring 4 as my rest api framework. Any more configurations need to be done on the project coding part?

Here are the steps I've done so far:

Any suggestions?

network response


Add the web.xml configuration I've tried to change cors.allowed.origins to *, to 127.0.0.1,192.168.1.100, all not working, remove credentials and maxage

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>http://192.168.1.100</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization</param-value>
  </init-param>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Suggested by Vishal, changing tomcat version from 8.0 to 8.5, still same issue

 XMLHttpRequest cannot load http://127.0.0.1:8080/leyutech-framework-gurunwanfeng/api/ad/getAdInfoByAdType.html?adType=0. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.100:8080' is therefore not allowed access. The response had HTTP status code 403.

Upvotes: 3

Views: 16430

Answers (2)

Shawn Zhou
Shawn Zhou

Reputation: 89

I've used the custom filter to accomplish this issue, I have no idea why offical tomcat cors filter is not working in my case, Any one can suggest the logic behind this, I am willing to try this out.

Original Post from Tobia

The code is modified from the link above.

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class SimpleCORSFilter 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, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(req, res);
    }

    public void destroy() {
        // TODO Auto-generated method stub

    }

    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}

web.xml configuration under current project

<filter>
    <filter-name>SimpleCORSFilter</filter-name>
    <filter-class>com.example.util.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>SimpleCORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Upvotes: 5

Mickael
Mickael

Reputation: 4558

I encountered this problem once and I developed a custom handler for a Jetty Web application.

Maybe it can help you.

CORSHandler.hava

import java.io.IOException;

import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.server.Request;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;

public class CORSHandler extends HandlerWrapper {

    public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
    public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
    public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";

    public CORSHandler() {
        super();
    }

    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        // Allow Cross-site HTTP requests (CORS)
        response.addHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "*");

        // Accept Content-Type in header
        response.addHeader(ACCESS_CONTROL_ALLOW_HEADERS, "content-type");

        // Accept GET, POST, PUT and DELETE methods
        response.addHeader(ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE");

        if (_handler!=null && isStarted())
        {
            _handler.handle(target,baseRequest, request, response);
        }
    }
}

Starter.java

import java.io.IOException;
import java.util.logging.Logger;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.SimpleFormatter;

import org.apache.cxf.transport.servlet.CXFServlet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.eclipse.jetty.server.handler.HandlerWrapper;

import com.example.config.AppConfig;
import com.example.handlers.CORSHandler;

import com.example.properties.*;

public class Starter {

    public static void main( final String[] args ) throws Exception {

        Server server = new Server( 8080 );

        // Register and map the dispatcher servlet
        final ServletHolder servletHolder = new ServletHolder( new CXFServlet() );

        HandlerWrapper wrapper = new CORSHandler();
        final ServletContextHandler context = new ServletContextHandler();

        context.setContextPath( "/" );
        context.addServlet( servletHolder, "/rest/*" );     
        context.addEventListener( new ContextLoaderListener() );

        context.setInitParameter( "contextClass", AnnotationConfigWebApplicationContext.class.getName() );
        context.setInitParameter( "contextConfigLocation", AppConfig.class.getName() );

        wrapper.setHandler(context);
        server.setHandler(wrapper);

        server.start();
        server.join();  
    }
}

Upvotes: 1

Related Questions