Spring Security 继承的Spring Framework的优良品质,设计了多种的扩展点,因此我们可以使用事件监听器来获知验证和授权事件,从而做一些日志记录操作。
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AbstractAuthenticationEvent;
public class AuthenticationEventLogger implements
ApplicationListener<AbstractAuthenticationEvent> {
@Override
public void onApplicationEvent(AbstractAuthenticationEvent event) {
System.out.println(event);
}
}
事件详解
不同的事件类型代表了不同的验证情况,从事件的设计上也能够看出Spring Security在设计时考虑周到。
org.springframework.security.authentication.event.AbstractAuthenticationEvent是共同的基础类型,代表了验证授权事件用于和其他种类的事件区别开来。
AbstractAuthenticationFailureEvent 在验证过程中发生异常会触发此类事件(抽象类型),
AuthenticationFailureBadCredentialsEvent(提供的凭据是错误的,用户名或者密码错误)
AuthenticationFailureCredentialsExpiredEvent(验证通过了,但是密码已经过期)
AuthenticationFailureDisabledEvent(验证过了但是账户被禁用)
AuthenticationFailureExpiredEvent(账户过期),
AuthenticationFailureLockedEvent(账户被锁定),
AuthenticationFailureProviderNotFoundEvent(配置错误,没有合适的AuthenticationProvider来处理登录验证)
AuthenticationFailureProxyUntrustedEvent(代理不受信任,用于Oauth、CAS这类三方验证的情形,多属于配置错误),
AuthenticationFailureServiceExceptionEvent(其他任何在AuthenticationManager中发生的异常都会被封装成此类,表示服务器500错误)
AuthenticationSuccessEvent(用户通过输入用户名和密码登录成功),
AuthenticationSwitchUserEvent(通过切换用户的手段来登录),
InteractiveAuthenticationSuccessEvent,(同样是登录成功,但表示通过自动交互的手段来登录成功,比如cookie自动登录)
SessionFixationProtectionEvent(当发生session fixation 攻击时触发的事件)