To handle session time out in case of AJAX requests, I have extended LoginUrlAuthenticationEntryPoint to handle it by returning HTTP status 401. But to my surprise the commence method is called when the first AJAX request is received on server. For the first time server still returns HTTP status 302 and then browser fetches login page but dies not redirect with status 200 OK.
Below is my AjaxAwareAuthenticationEntryPoint
And below is spring security configuration
Below is my firebug AJAX calls log
screeshot.jpg
Below is my AjaxAwareAuthenticationEntryPoint
Code:
public class AjaxAwareAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
public AjaxAwareAuthenticationEntryPoint(String loginUrl) {
super(loginUrl);
}
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
if (isAjax(request)) {
response.sendError(HttpStatus.UNAUTHORIZED.value(), "Please re-authenticate yourself");
} else {
super.commence(request, response, authException);
}
}
public static boolean isAjax(HttpServletRequest request) {
return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
}
}
And below is spring security configuration
Code:
<http auto-config="true" use-expressions="true" entry-point-ref="authenticationEntryPoint">
<intercept-url pattern="/index.jsp" access="permitAll" />
<intercept-url pattern="/qualifiers/**" access="hasRole('ROLE_USER')" />
<intercept-url pattern="/userpreference/**" access="hasRole('ROLE_USER')" />
<form-login login-page="/login.jsp" default-target-url="/index.jsp" authentication-success-handler-ref="authSuccessBean" authentication-failure-handler-ref="authFailureBean"
authentication-failure-url="/login.jsp?error=true" always-use-default-target="false" />
<logout logout-success-url="/login.jsp" delete-cookies="JSESSIONID" />
<remember-me />
<session-management invalid-session-url="/login.jsp">
<concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
</session-management>
</http>
<beans:bean id="authenticationEntryPoint" class="com.pcc.myapp.controller.auth.AjaxAwareAuthenticationEntryPoint">
<beans:constructor-arg name="loginUrl" value="/login.jsp" />
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="userLoginService">
<!-- <password-encoder hash="sha" /> -->
</authentication-provider>
</authentication-manager>
<beans:bean id="authFailureBean" class="com.pcc.myapp.controller.auth.AuthFailureHandler">
<beans:property name="defaultFailureUrl" value="/login.jsp?error=true" />
</beans:bean>
<beans:bean id="authSuccessBean" class="com.pcc.myapp.controller.auth.AuthSuccessHandler">
<beans:property name="defaultTargetUrl" value="/qualifiers/attributes.do" />
<beans:property name="alwaysUseDefaultTargetUrl" value="true" />
</beans:bean>
Below is my firebug AJAX calls log
screeshot.jpg