Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)

This is a very common error for people who are just getting started with Web Services, it’s really simple to solve but sometimes developers spend hours struggling to find a solution. It happens when you create a web service and tries to access it from a different application, it won’t work because you don’t have Cross-origin resource sharing (CORS) enabled, which means an application loaded in one domain cannot interact with resources from a different domain. All you have to do is to enable CORS.

How you can active it will depending on your scenario, in this tutorial I’m going to show how to enable CORS for a Java EE application running on Glassfish, I’m assuming you have an EJB RESTful web service similar to this one, and when other applications tries to consume it you see the Cross-Origin Request Blocked error on your firebug console, in this case all you have to do is to create a filter in your application, just create a class exactly like this one on your project:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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 CORSFilter implements Filter {
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, 
            FilterChain filterChain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, HEAD, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Accept, x-auth-token, "
                + "Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
        filterChain.doFilter(servletRequest, servletResponse);
    }
 
    @Override
    public void destroy() {
 
    }
 
}

Now you have to register the filter in your web.xml, copy the following code and replace “yourPackage” with your actual package name:

1
2
3
4
5
6
7
8
<filter>
    <filter-name>cors</filter-name>
    <filter-class>yourPackage.CORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

That’s it! Now your application will allow its resources to be shared with other domains.

Tutorial: Creating RESTful Web Services with EJB 3.1

RESTful web services has gained a lot of acceptance across the web, they are basically web services that follows the REST guidelines. In this short tutorial I’m going to create a very simple Hello World application that implements a RESTful Web Service using EJB 3.1.

I’m assuming that you already have your environment setup and also a Java EE project created and ready to use.
So let’s get started, the first step is to create a session bean that looks like this:

1
2
3
4
5
6
7
8
9
10
@Stateless
@Path("/sayHello")
public class HelloWorld {
 
   @GET
   @Produces("text/plain")
   public String sayHello() {
       return "Hello World!!";
   }
}

That’s really a straightforward implementation, we’ve used the annotation @Path to specify the URI path we’re going to use to access this service, we also created an operation accessible via HTTP GET (indicated by the @GET annotation), and lastly we specified the media type that this operation will produce, in this case it’s a plain text, but it could also be a JSON, XML, etc.
After creating the session bean, the second and last step is to register the servlet adaptor in the web.xml:

1
2
3
4
5
<servlet>        
     <servlet-name>ServletAdaptor</servlet-name>        
     <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>        
     <load-on-startup>1</load-on-startup>    
</servlet>

That’s it! You have already created a RESTful Web Service!!
Now if you deploy you project, you can go to your browser and type http://{projectURL}/sayHello, you’ll see the string “Hello World!!” displayed on the page.

Hope this post was helpful for you,
Till next Time!