Enterprise Java

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!

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button