Monday, May 13, 2013

Spring Security: Return a 401 UNAUTHORIZED for AJAX Requests

If you're using your SpringMVC app as a RESTful backend with an AJAX front end you might want a response that your AJAX client can handle besides a redirect to the login form.

We can do this by overriding the LoginUrlAuthenticationEntryPoint and seeing if a request is a AJAX call and if it is making sure we're sending back an appropriate response instead of the default behavior of redirecting.

If you're using a JS MV* type framework in a cross-domain app this info might be useful:
At the same time we can also pass cross-domain requests along to be handled by the right filters we have in place so that they don't get caught in the 401.  This isn't really a big deal but if you happen to have a cross-domain app using your server it doesn't look very good to be getting a 401 response for valid calls.  But, if you can set withCredentials: true on all requests that it might not be needed since Spring Security will then be able to see the logged in user's cookie when it sends the OPTIONS preflight request.

And here is the example you probably are wanting:

2 comments:

  1. Your article still saves lifes. Thank you! I implemented on a EJB aplication with uses ContainerRequestFilter as base for filter:
    if("OPTIONS".equals(requestContext.getMethod())) {
    requestContext.abortWith(Response.status(Response.Status.NO_CONTENT).build());
    }

    cheers

    ReplyDelete