我搜索了一个解决方案,但在任何地方都找不到,至少不是当前的解决方案,也不是使用非基于xml的Spring和Spring Security配置的解决方案。
我需要实现一个将在Spring注销处理程序之前使用的处理程序。我已经阅读了很多关于LogoutSuccessHandler的文章,但这是在注销过滤器成功注销后调用的,我需要访问存储在用户会话中的用户数据以执行一些数据库条目,站点注销信息等。一旦Spring注销用户,此会话就会丢失,因此必须在此之前。
我尝试创建自己的自定义注销类,并在我的应用程序配置类中定义它,如下所示:
@Bean
public CustomLogoutHandler customLogoutHandler() {
return new CustomLogoutHandler();
}
我的类扩展了LogoutHandler,就像spring文档所说的:
public class CustomLogoutHandler extends LogoutHandler {
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
// business logic here
}
}
这仍然不起作用。我在代码中放置了一个断点,它永远不会被拾取。有人知道是什么导致了这一点吗?或者我需要做什么才能让它工作?
要使用实现Spring的LogoutHandler.class的自定义注销处理程序,你需要让Spring知道你在配置文件中使用了你自己的logout handler。在安全配置文件中:
public class SecurityConfig extends WebSecurityConfigurerAdapter {
... // Other methods here
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.otherConfigOptions
.logout()
.addLogoutHandler(customLogoutHandler()) <- custom handler
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.otherConfigOptions....
}
}
定义bean,我把我的放在SecurityConfig.class但我认为你可以把它放在Web或应用程序配置类中,这取决于你如何设置你的项目。
@Bean
public CustomLogoutHandler customLogoutHandler() {
return new CustomLogoutHandler();
}
然后,创建自定义注销处理程序.class,确保实现注销处理程序并覆盖注销方法。在这里,可以使用身份验证类访问已添加到用户请求范围的任何内容。
public class CustomLogoutHandler implements LogoutHandler {
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
// business logic here
}
}
您还应该看看这个问答,它讨论了Spring中自定义处理程序映射的顺序。
我希望这能有所帮助。