Reputation: 1373
I am trying to save a log into the database when the user clicks the logout button. For the Login I use the @Before... method and AOP is executing this method and saves the record into the database.
But for the logout is a little different because I don´t have a particular logout method, instead the logout is handled by the Spring Security:
// ...
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
// ...
What is the best practice in order to execute a method before the logout occur?
Thanks, R.
Upvotes: 0
Views: 1295
Reputation: 81
With spring aop, you can do it this way:
@Before("execution(* org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler.logout(..))")
public void beforeLogout(JoinPoint joinPoint) throws Throwable {
System.out.println(
">>> Aspect : User " + SecurityContextHolder.getContext().getAuthentication().getName() + " successfully logged out.");
}
Upvotes: 3
Reputation: 589
Your approach is good, i have explicitly mapped spring security logout success url to spring controller like below example :
@RequestMapping(value="/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/login?logout";//You can redirect wherever you want, but generally it's a good practice to show login screen again.
}
<logout
logout-success-url="/logout"
delete-cookies="JSESSIONID" />
Inside controller method you do your audit stuff.
Upvotes: 0
Reputation: 1373
Finally I got a solution for this problem using a CustomLogoutSuccessHandler implementing the LogoutSuccessHandler interface, but I could not use AOP because when the method is invoked the Security Handler can no longer access the user information because is disconnected. But the interface method onLogoutSuccess came with the Authentication parameter which is I could use to retrieve the user info and store it into the database before close the http session.
If there are any other solutions please respond.
Thanks R.
Upvotes: 1