Interesting CORS issue – Jersey Web Services, Spring Security, Phone Gap and Ajax - Ideas2IT

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

Share This

In one of our iOS mobile development projects, we faced the cross domain error. Cross domain issue typically occurs when the application is hosted on one domain, the webservices 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 modified existing security xml helped us resolved the issue and moreover the authentication was also retained.

I have detailed out 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" />

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