Sunday 20 December 2015

Enabling CORS (Cross Origin Resource Sharing) headers in java rest services

CORS (Cross Origin Resource Sharing) is a mechanism supported by W3C to enable cross origin requests in web-browsers. CORS requires support from both browser and server to work. 

CORS implementation is required to access rest services hosted in one domain (ip address) from another domain (ip address). The cross domain access will be disabled by default. This will not be an issue until the services are accessed within the same domain. The services can be accessed from different domains using the below mechanism.

Java rest service response should return Access-Control-Allow-Origin: * in the header in order to allow angular js and other applications to access rest services.
This can be done manually, by adding the below line of code, to each and every rest service.
          
 return Response.status(200).header("Access-Control-Allow-Origin", "*").build()

But doing this will be time consuming, if the number of rest services is many.
Instead of doing it manually, we can add this header to the rest services programmatically. This can be done by using the following class in the web project that contains the rest service application.

import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
 @Provider
 public class CORSFilter implements ContainerResponseFilter {
   @Override
    public void filter(final ContainerRequestContext request,  final 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");
       response.getHeaders().add("Access-Control-Max-Age", "1209600");
    }
}
Note :
This class need not be invoked manually.  @Provider annotation, will automatically call this class, every time the rest service returns a response.
 To enable security, instead of adding * to Access-Control-Allow-Origin, we can give the specific address, that hosts the angular js program.

No comments:

Post a Comment