美文网首页
Spring-Security-文档笔记之Authenticat

Spring-Security-文档笔记之Authenticat

作者: xzz4632 | 来源:发表于2021-08-06 16:49 被阅读0次

    1. 介绍

    每次身份验证成功或失败,将分别触发AuthenticationSuccessEventAuthenticationFailureEvent。要监听这些事件, 需要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;
    }

    相关文章

      网友评论

          本文标题:Spring-Security-文档笔记之Authenticat

          本文链接:https://www.haomeiwen.com/subject/zdqivltx.html