Spring AOP Spring Security

问题描述 投票:-1回答:3

我试图在用户单击注销按钮时将日志保存到数据库中。对于登录我使用@Before ...方法,AOP正在执行此方法并将记录保存到数据库中。

但是注销有点不同,因为我没有特定的注销方法,而是注销由Spring Security处理:

   // ...
   .and()
   .logout()
   .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
   .logoutSuccessUrl("/")
   // ...

在注销发生之前执行方法的最佳做法是什么?

谢谢,R。

spring-security spring-aop
3个回答
1
投票

最后,我使用实现LogoutSuccessHandler接口的CustomLogoutSuccessHandler获得了此问题的解决方案,但我无法使用AOP,因为在调用该方法时,安全处理程序无法再访问用户信息,因为已断开连接。但onLogoutSuccess的接口方法附带了Authentication参数,我可以使用它来检索用户信息并在关闭http会话之前将其存储到数据库中。

如果有任何其他解决方案,请回复。

谢谢R.


1
投票

有了spring aop,你可以这样做:

@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.");
}

0
投票

您的方法很好,我已将spring security logout成功URL明确映射到spring控制器,如下例所示:

@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" />

在控制器内部,您可以执行审计。

© www.soinside.com 2019 - 2024. All rights reserved.