david's daily developer note

[BE] Spring security AuthenticationSuccessEvent & SessionDestroyedEvent 본문

[Develop] Web/Back-end

[BE] Spring security AuthenticationSuccessEvent & SessionDestroyedEvent

mouse-david 2023. 10. 30. 23:23
728x90

Spring security 사용자 인증 성공과 사용자 세션 만료를 트랙킹 하는 코드를 간단히 메모한다.

사용자 인증 성공 추적

SecurityConfig에 Bean등록 (AuthenticationEventPublisher)

  @Bean
    public AuthenticationEventPublisher authenticationEventPublisher
            (ApplicationEventPublisher applicationEventPublisher) {
        return new DefaultAuthenticationEventPublisher(applicationEventPublisher);
    }

 EventListener 등록  (AuthenticationSuccessEvent )

@Component
public class UserAuthenticationEvents {

    @EventListener
    public void handleAuthenticationSuccessEvent(AuthenticationSuccessEvent event) {
        Authentication authentication = event.getAuthentication();
        //authentication.getPrincipal());
    }
}

 

사용자 세션 만료 추적 

사용자가 직접 로그아웃 하거나, 세션이 만료된 경우를 추적한다.

SecurityConfig에 Bean등록 (HttpSessionEventPublisher)

  @Bean
    public ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
        return new ServletListenerRegistrationBean<>(new HttpSessionEventPublisher());
    }

SessionDestroyedEvent Custom Listener를 등록  (SessionDestroyedEvent)

@Component
public class UserSessionDestroyedEvent implements ApplicationListener<SessionDestroyedEvent> {

    @Override
    public void onApplicationEvent(SessionDestroyedEvent event) {
        List<SecurityContext> securityContextList = event.getSecurityContexts();
        for (SecurityContext securityContext : securityContextList) {
            //(UserDetails) securityContext.getAuthentication().getPrincipal();
        }
    }
}

 

 

728x90