Friday, January 9, 2015

Custom CORS filter in java

Implement CORS Filter in Java.
When you want to make a Cross Domain Call from angular.js to a Jboss (or Any server). You can write a simple servlet filter to achieve this.
Add a new Servlet like below
package com.rest.cors;
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 {
        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-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
        filterChain.doFilter(servletRequest, servletResponse);
    }
    @Override
    public void destroy() {
    }
}

Add a Filter entry in the web.xml of your war file
    <filter>
        <filter-name>cors</filter-name>
        <filter-class>com.rest.cors.CorsFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>cors</filter-name>
        <url-pattern>* /*</url-pattern>
    </filter-mapping>

This will ensure that CORS Filter applied to all, REST APIs and Servlets’.

Available headers are,
Access-Control-Allow-Origin – you can set the originating domain info here
Access-Control-Allow-Credentials – set to true by default
Access-Control-Expose-Headers
Access-Control-Max-Age
Access-Control-Allow-Methods
Access-Control-Allow-Headers


If you intend to use xml/json in content-type, please make sure you allow OPTION as in the above sample.

No comments:

Post a Comment