Java – Spring security Session Timeout handling for Ajax calls

ajaxjavaspringspring-security

I have create webapp where I have used Spring Security and I have added 2 custom filters to spring-security.xml file shown below.

    <security:custom-filter ref="authenticationFilter" position="FORM_LOGIN_FILTER"/>
    <security:custom-filter ref="concurrencyFilter" position="CONCURRENT_SESSION_FILTER"/>

It works for non ajax requests. When I try to send AJAX request while session is already expired action returns me login page as html which as response is loaded into the div element.
I have already searched for solution and found this link Session Timeout handling for Ajax calls where defined functionality returns status code and this code used in javascript side in order to navigate user to login page.

My question is:

In which order authenticationFilter, concurrencyFilter and ajaxTimeoutRedirectFilter have to be defined in spring-security.xml file to make request pipeline correctly to be handled?

Best Answer

Look at 3) Filter configuration :

The idea is to add the above custom filter in the Spring Security filter chain. The order in the filter chain is crucial. Our filter should intercept the session timeout for Ajax calls before the vanilla ExceptionTranslationFilter in order to send the custom HTTP error code.

in xml config add :

<custom-filter ref="ajaxTimeoutRedirectFilter" after="EXCEPTION_TRANSLATION_FILTER"/>

in java config add :

@Bean
public Filter ajaxTimeOutRedirectFilter() {
    AjaxTimeOutRedirectFilter f = new AjaxTimeOutRedirectFilter();
    //f.setCustomSessionExpiredErrorCode(901);
    return f;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .addFilterAfter(ajaxTimeOutRedirectFilter(), ExceptionTranslationFilter.class)
        ...
        ...
}

it works for me, thanks to DuyHai's Java Blog and Demo application for the article