Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

java - Origin is not allowed by Access-Control-Allow-Origin - how to enable CORS using a very simple web stack and guice

I am not sure if the issue is the technologies involved, or my understanding of the technologies.

I have an html5 application written in javascript and html hosted on an apache 2.2 server.

I have a java application written in java using jetty, guice, jackson, jersey that hosts a simple REST service.

Both applications run on the same box, one on port 80 (pure html5 application hosted on apache), the other on 8080 (pure java application hosted on jetty/guice)

I believe the answer is in the headers im sending back. The CORS headers tell a browser that you allow outside applications to hit your api. I cannot seem to figure out how to configure my Jetty, Guice server to return the correct CORS headers.

I am using an imbeded Jetty server so I do not have a web.xml file to add the headers with.

It also might be something to do with how the HTML5 application server (in this case apache 2.2) is serving the application.

The apache httpd.conf file has the entry:

LoadModule headers_module modules/mod_headers.so

<IFModule mod_headers>
    Header add Access-Control-Allow-Origin "*"
    Header add Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE, HEAD
    Header add Access-Control-Allow-Headers: X-PINGOTHER
    Header add Access-Control-Max-Age: 1728000  
</IfModule>

in my guice servlet configuration I have the following:

public class RestModule extends ServletModule{

    @Override
    protected void configureServlets() {
        bind(QuestbookService.class);

        // hook Jersey into Guice Servlet
        bind(GuiceContainer.class);

        // hook Jackson into Jersey as the POJO <-> JSON mapper
        bind(JacksonJsonProvider.class).in(Scopes.SINGLETON);

        Map<String, String> guiceContainerConfig = new HashMap<String, String>();
        guiceContainerConfig.put(ResourceConfig.PROPERTY_RESOURCE_FILTER_FACTORIES,
            HttpStatusCodeMetricResourceFilterFactory.class.getCanonicalName());
        serve("/*").with(GuiceContainer.class, guiceContainerConfig);
    }
}

I think the problem is in my guice config since I don't have a place to set the response headers.

I am using an embedded jetty server and thus I figured dev mode would bypass the whole check, but I could be wrong.

Thank you for any advice.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Do to the specific requirements of my application. The server needs to be seporate completly seporate from the client. The client should be able to connect to the communication server via any method it can.

Since the first implementation of this application is going to be REST driven, I need to be able to accept rest from anywhere.

In addition, I want a completly xml-less config, so I use Guice with an imbedded Jetty server. Since I do not have a web.xml file, I could not figure out how to set the headers to allow CORS.

After alot of trial and error, and reading the guice documentation, I found how to add the CORS headers to the response leaving the server.

The Guice ServletModule class allows you to add filters to your servlet context. This allows me to have all requests pass through a given servlet.

Since I am trying to build a rest application that responds to CORS requests, i needed a filter that added the cors headers to the response of any request.

So to enable cors in my embedded server using guice I built a filter that looks like this:

@Singleton
public class CorsFilter implements Filter{

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain filterChain) throws IOException, ServletException {

        if(response instanceof HttpServletResponse){
        HttpServletResponse alteredResponse = ((HttpServletResponse)response);
        addCorsHeader(alteredResponse);
    }

    filterChain.doFilter(request, response);
    }

    private void addCorsHeader(HttpServletResponse response){
        //TODO: externalize the Allow-Origin
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
        response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
        response.addHeader("Access-Control-Max-Age", "1728000");
    }

    @Override
    public void destroy() {}

    @Override
    public void init(FilterConfig filterConfig)throws ServletException{}
}

Guice provides an abstract class that allows you to configure the Guice Servlet.

The configuration module looks like this:

public class RestModule extends ServletModule{

    @Override
    protected void configureServlets() {
        bind(MyServiceClass.class);

        // hook Jersey into Guice Servlet
        bind(GuiceContainer.class);

        // hook Jackson into Jersey as the POJO <-> JSON mapper
        bind(JacksonJsonProvider.class).in(Scopes.SINGLETON);

        Map<String, String> guiceContainerConfig = new HashMap<String, String>();

        serve("/*").with(GuiceContainer.class, guiceContainerConfig);

        filter("/*").through(CorsFilter.class);
    }
}

Now guice will add cors headers to every response. Allowing my pure HTML 5 application to talk to it, no matter where it is being served.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...