Spring-Security:身份验证后的调用方法

2022-09-01 16:42:59

我想跟踪用户何时登录到我的应用程序。我有一些代码,我想在用户通过身份验证后立即执行。问题是,我不知道这应该叫什么。spring-security有没有办法在身份验证后调用方法?


答案 1

可能对某人有用...在 Spring 3 的情况下,配置安全性:

<security:http use-expressions="true" auto-config="true">
    <security:intercept-url pattern="..."/>
    <security:form-login
            authentication-failure-handler-ref="authFailureHandler"
            authentication-success-handler-ref="authSuccessHandler"/>
    <security:logout success-handler-ref="logoutSuccessHandler"
            invalidate-session="true"/>
    <security:session-management session-fixation-protection="newSession"/>
</security:http>

<bean id="authFailureHandler" class="mine.AuthenticationFailureHandlerImpl"/>
<bean id="authSuccessHandler" class="mine.AuthenticationSuccessHandlerImpl"/>
<bean id="logoutSuccessHandler" class="mine.LogoutSuccessHandlerImpl"/>

并实现适当的类:

public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //do what you want with 
        response.getOutputStream().write("success".getBytes());
    }
}

您可以通过该 xml 配置链接资源。


答案 2

最好的方法是创建一个应用程序侦听器,并将其注册到 spring 安全上下文中。

import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;

public class AuthenticationSuccessListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {

    @Override
    public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) {
        System.out.println("User Logged In");

    }
}

确保将上述类添加弹簧安全性.xml作为豆子。您可以侦听许多其他类型的安全事件侦听器,请检查类型层次结构以获取可以侦听的所有类型的安全事件的列表。


推荐