Ideas2IT rewards key players with 1/3rd of the Company in New Initiative.  Read More >
Back to Blogs

Interesting CORS Issue – Jersey Web Services, Spring Security, Phone Gap and Ajax

In one of our iOS mobile development projects, we faced a cross-domain error. The cross-domain issue typically occurs when the application is hosted on one domain, the web services is hosted on a different domain and we are trying to make an Ajax call to get the response. In our case, the hybrid phone gap code was making an Ajax call to our web services hosted using Jersey with spring basic authentication and ended with a CORS error. The HTTP method that was invoked was OPTIONS and not GET or POST. The web service was independently tested using the Rest Console and it worked fine.Resolving this issue was one aspect but we still needed to retain the security authentication. Otherwise, we would end up exposing an unauthenticated web service which is a threat.Adding a new filter class and modifying existing security xml helped us resolve the issue and moreover the authentication was also retained.I have detailed the steps in detail below:a) Add a new filter class. Please see below for the code snippetpublic class <> extends OncePerRequestFilter
static final String ORIGIN = "Origin";
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
if (request.getHeader(ORIGIN).equals("null"))
String origin = request.getHeader(ORIGIN);
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
if (request.getMethod().equals("OPTIONS"))
try {
} catch (IOException e) {
} else
filterChain.doFilter(request, response);
}b) Along with your other configurations, add the below code inside the configuration<security:custom-filter ref="corsHandler" after="PRE_AUTH_FILTER"/>c) Add the bean definition for this custom filter in the spring context<bean id="corsHandler" />

About Ideas2IT:Are you looking to build a great product or service? Do you foresee technical challenges? If you answered yes to the above questions, then you must talk to us. We are a world-class Custom dot net development company. We take up projects that are in our area of expertise. We know what we are good at and more importantly what we are not. We carefully choose projects where we strongly believe that we can add value. And not just in engineering but also in terms of how well we understand the domain. Book a free consultation with us today. Let’s work together.

Ideas2IT Team

Connect with Us

We'd love to brainstorm your priority tech initiatives and contribute to the best outcomes.