Spring, REST, Ajax and CORS

Assuming you’re working on a project based on JavaScript for the client side and who makes ajax requests to a server through rest web services, you may encounter some troubles especially if both sides are on a separate domain.

Indeed, for security reasons, ajax requests from one domain A to a different domain B are not authorized.

Fortunately, the W3C introduced what is known as CORS (Cross Origin Resource Sharing) which offers the possibility for a server to have a better control of cross domain requests.

To do that, the server must add HTTP headers to the response, indicating to the client side which are the allowed origins.

Moreover, if you use custom headers, you browser will not be able to read them for security matters, so you must specify which headers to expose. So, if in your JavaScript code you can’t retrieve your custom http header value, you should read what comes next

List of headers:

Access-Control-Allow-Origin

Access-Control-Allow-Origin: <origin> | *

The origin parameter specifies a URI that may access the resource.  The browser must enforce this.  For requests without credentials, the server may specify “*” as a wildcard, thereby allowing any origin to access the resource.

Access-Control-Expose-Headers

Access-Control-Expose-Headers: X-My-Header

This header lets a server whitelist headers that browsers are allowed to access. It is very usefull when you add custom headers, because by adding them to the ” Access-Control-Expose-Headers” header you can be sure that your browser will be able to read them.

Access-Control-Max-Age

Access-Control-Max-Age: <delta-seconds>

This header indicates how long the results of a preflight request can be cached.

Access-Control-Allow-Methods

Access-Control-Allow-Methods: <method>[, <method>]*

Specifies the method or methods allowed when accessing the resource.  This is used in response to a preflight request.  The conditions under which a request is preflighted are discussed above.

Access-Control-Allow-Headers

Access-Control-Allow-Headers: <field-name>[, <field-name>]*

Used in response to a preflight request to indicate which HTTP headers can be used when making the actual request.

Now let’s see how to add this headers with Spring

First we need to create a class implementing the Filter interface:

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;

public class CORSFilter implements Filter {

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) res;
                HttpServletRequest request= (HttpServletRequest) req;

                  response.setHeader("Access-Control-Allow-Origin", "*");
                  response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                  response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
                  response.setHeader("Access-Control-Expose-Headers", "x-requested-with"); chain.doFilter(req, res);
        }
}

Now, we just have to add our filter to the servlet context:

@Configuration
public class ServletConfigurer implements ServletContextInitializer {
     @Override
    public void onStartup(javax.servlet.ServletContext servletContext) throws ServletException {
       servletContext.addFilter("corsFilter", new CORSFilter());
    }
}

And that’s all folks, you’re now able to make cross domain requests and use custom http headers!

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


4 × = twenty four



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books