Spring Security provides fantastic functionality for authentication and authorisation for Java developers. After adding Spring jar files, fairly simple configuration and a login page you can save days of development. However, problems show up when it comes to adding awesome ajax features in your website. The basic settings which is mentioned in most of the blogs including tutorials from Spring Community configures Spring Security in a way that unauthorised requests are automatically responded with a redirection to login URL that is set in the configuration. This will mess up requests that are meant to return valid JSON objects to be used in client side. Therefore, we are required to extinguish these two types of requests. Firstly a customised AuhenticationEntryPoint must be implemented :
public class CustomAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request,HttpServletResponse response,
org.springframework.security.core.AuthenticationException authException) throws IOException, ServletException {
String xrequestedWith = ((HttpServletRequest) request).getHeader("x-requested-with");
if (xrequestedWith != null && xrequestedWith.equals("XMLHttpRequest")
&& authException != null) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
else{
super.commence(request, response, authException);
}
}
}
In the above sample we are examining the request to see if it is an Ajax request and if there is an exception we simply send an error.
Inside the configuration files, an instance of this class needs to be set as the entry point :
<bean id="customAuthenticationEntryPoint" >
<property name="loginFormUrl" value="/login" />
</bean>
<http use-expressions="true" entry-point-ref="customAuthenticationEntryPoint">
.... intercept urls, etc
</http>
The error then can easily be identified in client side and dealt with accordingly:
$.getJSON(url, function(data) { /*do your thing here*/}) .error(function(jqXHR, textStatus, errorThrown) { /* check jqXHR.status here and do the other thing*/ ); } );
Now we can enjoy Ajax with awesome Spring.