弹簧安全性自定义注销处理程序

2022-09-02 04:03:54

如何将我自己的注销处理程序添加到春季安全性的LogoutFilter中?谢谢!


答案 1

以下解决方案对我有用,可能会有所帮助:

  1. 扩展 SimpleUrlLogoutSuccessHandler 或实现 LogoutHandler

    public class LogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
    
       // Just for setting the default target URL
       public LogoutSuccessHandler(String defaultTargetURL) {
            this.setDefaultTargetUrl(defaultTargetURL);
       }
    
       @Override
       public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    
            // do whatever you want
            super.onLogoutSuccess(request, response, authentication);
       }
    }
    
  2. 添加到您的弹簧安全配置:

    <security:logout logout-url="/logout" success-handler-ref="logoutSuccessHandler" />
    <bean id="logoutSuccessHandler" class="your.package.name.LogoutSuccessHandler" >
        <constructor-arg value="/putInYourDefaultTargetURLhere" />
    </bean>
    

答案 2

在Spring Security Forum上看到这篇文章的答案:

XML 定义:

<beans:bean id="logoutFilter" class="org.springframework.security.ui.logout.LogoutFilter">
    <custom-filter position="LOGOUT_FILTER"/>
    <beans:constructor-arg index="0" value="/logout.jsp"/>
    <beans:constructor-arg index="1">
        <beans:list>
            <beans:ref bean="securityContextLogoutHandler"/>
            <beans:ref bean="myLogoutHandler"/>
        </beans:list>
    </beans:constructor-arg>
</beans:bean>

<beans:bean id="securityContextLogoutHandler" class="org.springframework.security.ui.logout.SecurityContextLogoutHandler"/>

<beans:bean id="myLogoutHandler" class="com.whatever.CustomLogoutHandler">
    <beans:property name="userCache" ref="userCache"/>
</beans:bean>

注销处理程序类:

public class CustomLogoutHandler implements LogoutHandler {
    private UserCache userCache;

    public void logout(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) {
        // ....
    }

    @Required
    public void setUserCache(final UserCache userCache) {
        this.userCache = userCache;
    }
}

推荐