Spring-Security-文档笔记之Authenticat
1. 介绍
每次身份验证成功或失败,将分别触发AuthenticationSuccessEvent
或AuthenticationFailureEvent
。要监听这些事件, 需要AuthenticationEventPublisher
, 默认实现为DefaultAuthenticationEventPublisher
.
@Bean
public AuthenticationEventPublisher authenticationEventPublisher
(ApplicationEventPublisher applicationEventPublisher) {
return new DefaultAuthenticationEventPublisher(applicationEventPublisher);
}
然后可通过@EventListener
监听事件:
@Component
public class AuthenticationEvents {
@EventListener
public void onSuccess(AuthenticationSuccessEvent success) {
// ...
}
@EventListener
public void onFailure(AuthenticationFailureEvent failures) {
// ...
}
}
2. 事件映射
DefaultAuthenticationEventPublisher默认可发布以下事件 :
异常 | 事件 |
---|---|
BadCredentialsException | AuthenticationFailureBadCredentialsEvent |
UsernameNotFoundException | AuthenticationFailureBadCredentialsEvent |
AccountExpiredException | AuthenticationFailureExpiredEvent |
ProviderNotFoundException | AuthenticationFailureProviderNotFoundEvent |
DisabledException | AuthenticationFailureDisabledEvent |
LockedException | AuthenticationFailureLockedEvent |
AuthenticationServiceException | AuthenticationFailureServiceExceptionEvent |
CredentialsExpiredException | AuthenticationFailureCredentialsExpiredEvent |
InvalidBearerTokenException | AuthenticationFailureBadCredentialsEvent |
这个publisher精确匹配异常,即这些异常的子类也不会产生事件。提供附加映射:
@Bean
public AuthenticationEventPublisher authenticationEventPublisher
(ApplicationEventPublisher applicationEventPublisher) {
Map<Class<? extends AuthenticationException>,
Class<? extends AuthenticationFailureEvent>> mapping =
Collections.singletonMap(FooException.class, FooEvent.class);
AuthenticationEventPublisher authenticationEventPublisher =
new DefaultAuthenticationEventPublisher(applicationEventPublisher);
authenticationEventPublisher.setAdditionalExceptionMappings(mapping);
return authenticationEventPublisher;
}