/ Technology

Custom LogoutHandler in Spring 4

I needed to inject some logic after a user logs out. I am using Spring 4 and this worked. I initially tried the LogoutSuccessHandler but I needed some property in the session which prevented me from using that. So I finally implemented it using this code.

Note that this code executes before Spring logs out the user. If you need to do something after the user logs out, you need the LogoutSuccessHandler instead.

Create a new class SecurityContextLogoutHandler.java

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

@Component
public class CustomLogoutHandler extends SecurityContextLogoutHandler{
		
	@Override
	public void logout(HttpServletRequest request, HttpServletResponse response,
			Authentication auth) {
		 //do your custom thing here
		
	}
}

Then configure it as a filter in application-security-context.xml

<http>
	<custom-filter position="LOGOUT_FILTER" ref="logoutFilter"/>
</http>

<beans:bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
		<beans:constructor-arg value="/logout-success"/>
		<beans:constructor-arg>
			<beans:bean class="com.melvinvivas.CustomLogoutHandler"/>
		</beans:constructor-arg>
		<beans:property name="filterProcessesUrl" value="/logout"/>
</beans:bean>

I hope this helps other developers who have the same requirement.

Cheers!