Spring 安全性 Java 配置自定义注销处理程序不工作

Spring Security Java Config Custom Logout Handler Not Working

我已经搜索了一种解决方案,但在任何地方都找不到,至少找不到当前的解决方案或使用非 xml 基于 Spring 和 Spring 安全性的解决方案配置。

我需要实现一个将在 spring 注销处理程序之前使用的处理程序。我已经阅读了很多关于 LogoutSuccessHandler 的文章,但是在注销过滤器成功注销后调用它,我需要访问存储在用户会话中的用户数据以执行一些数据库条目、站点注销信息等。这个会话一旦 spring 注销用户,它就会丢失,所以它必须在那之前。

我尝试创建自己的自定义注销 class 并在我的应用程序配置 class 中定义它,如下所示:

@Bean
public CustomLogoutHandler customLogoutHandler() {
    return new CustomLogoutHandler();
}

我的 class 扩展了 LogoutHandler,就像 spring 文档所说的那样:

public class CustomLogoutHandler extends LogoutHandler {

    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        // business logic here
    }
}

这仍然无效。我在代码中放置了一个断点,但它永远不会被拾取。有没有人知道是什么导致了这个或者我需要做什么才能让它工作?

要使用您自己的实现 Spring 的 LogoutHandler.class 的自定义注销处理程序,您需要在注销选项下的配置文件中让 Spring 知道您正在使用自己的注销处理程序使用 .addLogoutHandler。我想你错过了这一步。在安全配置文件中:

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 或应用程序配置中 class,具体取决于您设置项目的方式。

@Bean
public CustomLogoutHandler customLogoutHandler() {
    return new CustomLogoutHandler();
}

然后,创建自定义LogoutHandler.class,确保实施 LogoutHandler 并覆盖注销方法。在这里,您可以使用身份验证 class 访问您已添加到用户请求范围的任何内容。

public class CustomLogoutHandler implements LogoutHandler {
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

        // business logic here
    }
}

您还应该看看这个 question and answer,它讨论了 Spring 中自定义处理程序映射的顺序。

希望对您有所帮助。