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

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

Share This

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 snippet

public 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get Instant Pricing Straight to Your Inbox

Let us know what your needs are and get a quote sent straight to your inbox.

Thank you for contacting us

Get Pricing Sent Straight to Your Inbox