What is Access Control Allow Origin and how to use CORS in Java Spring

When a javascript client tries to  consume data from another application or some resource on a server through a REST API, the server responds with a  Access-Control-Allow-Origin  response header to tell the client that the content of this page is accessible to certain origins. The origins can be any  client that sends a request to the server to fetch some resource. The clients that are allowed to access can also be specified. But by default, clients are not allowed to fetch the resource from the server.

This Access-Control-Allow-Origin  is a Cross Origin Resource Sharing (CORS) and the CORS filter must be implemented to send a response from the server while building RESTful Web Services.  The way this works is, when a client makes a request for a resource, it sends the Origin header in the request. The server validates this origin and decides to allow the request or not. If it decides  to allow, then it responds  with the Access-Control-Allow-Origin in the header and then upon receiving this, the browser  matches the origin and allows the request. If the browser finds that the origin matches, it allows the request to be completed, else it throws an error.

Here is an example of a GET request made to a REST service and the corresponding response given by the server. Here, the Origin matches the one mentioned by the server.

Request:

GET /test/test.json  HTTP/1.1/
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) Gecko/
Firefox/3.5.5 (.NET CLR 3.5.30729)
Accept: application/json
Origin: http://examplesite.com

Response: 

HTTP/1.1 200 OK
Content-Type: Application/json;character-set=UTF-8
Date: Sun,  30 Aug 2015
Server:Apache-coyote/1.1
Access-Control-Allow-Origin:  http://examplesite.com

Thus, the request is allowed in the above case. If your server should allow requests from all origins, then you can set:
Access-Control-Allow-Origin: “*”

Here the “*” indicates all origins to be allowed to complete their request.

If you are building a REST service in spring, you can create a simple or complex CORS filter. This filter will then help your server respond to request accordingly. Following is a simple program given by the Official Spring Documentation, which allows all origins to access a resource from your server.

package hello;
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;
import org.springframework.stereotype.Component;

@Component
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 init(FilterConfig filterConfig) {}

	public void destroy() {}

This Program allows any kind of origin to  send  GET, POST, OPTIONS and DELETE requests  and serves them accordingly. The Access-Control-Max-Age field makes sure that the access control is alive for 1 hour or 3600 seconds.

Without setting the CORS filter, any client , be it a web front end built using AngularJS or a simple JavaScript client will not be able to fetch the data. and you might get an error thrown by he browser.

Source: Spring Documentation 1, Spring Documentation 2, StackOverFlow

akshay pai

I am a data science engineer and I love working on machine learning problems. I have experience in computer vision, OCR and NLP. I love writing and sharing my knowledge with others. This is why I created Source Dexter. Here I write about Python, Machine Learning, and Raspberry Pi the most. I also write about technology in general, books and topics related to science. I am also a freelance writer with over 3 years of writing high-quality, SEO optimized content for the web. I have written for startups, websites, and universities all across the globe. Get in Touch! We can discuss more.

Leave a Reply