Q:

Spring security redirect when maximum sessions for this principal exceeded

So user login -> closes the browser -> opens browser one more time -> error appears:
HTTP Status 401 - Authentication Failed: Maximum sessions of 1 for this principal exceeded

What I need is to capture this event that session is invalid, remove all sessions for this user and redirect to normal login page
spring security config:
        <http auto-config="true" use-expressions="true">
                <session-management session-fixation-protection="migrateSession">
                    <concurrency-control max-sessions="1" error-if-maximum-exceeded="true"/>
                </session-management>   
                <intercept-url pattern="/login" access="hasRole('ROLE_ANONYMOUS')" requires-channel="any"/> 

    <!--<custom-filter after="CONCURRENT_SESSION_FILTER" ref="sessionExpiration" /> -->
    <!-- .... -->

        </http>

<beans:bean id="sessionExpiration" class="com.test.security.SessionExpirationFilter">
    <beans:property name="expiredUrl">
            <beans:value>/login</beans:value>
        </beans:property>
 </beans:bean>

I tried to implement some filter, but it always shows that session is null: 
public class SessionExpirationFilter implements Filter, InitializingBean {
    private String expiredUrl;

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String path = httpRequest.getServletPath();
        HttpSession session = httpRequest.getSession(false);

        System.out.println(session);
        if (session == null && !httpRequest.isRequestedSessionIdValid()) {              
            SecurityContextHolder.getContext().setAuthentication(null);
            String targetUrl = httpRequest.getContextPath()
                    + expiredUrl;
            httpResponse.sendRedirect(httpResponse.encodeRedirectURL(targetUrl));
            return;
        }
        chain.doFilter(request, response);
    }

    public void setExpiredUrl(String expiredUrl) {
        this.expiredUrl = expiredUrl;
    }
}

A:

From what I understood, you want to invalidate the previous session if it User's session exceeds 'max-sessions'. Set the property 'error-if-maximum-exceeded' to false. Spring security automatically invalidates previous session.
If you are trying to do something different,

Extend ConcurrentSessionControlStrategy class, and override
'allowableSessionsExceeded' method.
Specify the bean reference of the above as 'session-authentication-strategy-ref' attribute value of 'session-management'

.

