0

I try to log when user is successfully logged with Spring Security. I use Logging Aspect :

@Aspect
@Component
public class LoggingAspect {
static Logger log = Logger.getLogger(LoggingAspect.class);

@Before("execution(* com.jle.athleges.web.controller.MemberController.*(..))")
public void logBefore(JoinPoint joinPoint) {
    log.info("INFO - logBefore() is running!");
    log.info(joinPoint.getSignature().getName());
}

@AfterReturning(pointcut = "execution(* org.springframework.security.authentication.AuthenticationManager.authenticate(..))", returning = "result")
public void after(JoinPoint joinPoint, Object result) throws Throwable {
    log.info(">>> user: " + ((Authentication) result).getName());
}

@Around("execution(* org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler.onAuthenticationSuccess(..))")
public void onAuthenticationSuccess(){
    log.info(">>> user " + (SecurityContextHolder.getContext().getAuthentication().getName()) + " is now connected");
}
}

Method after is running fine but log twice. I try with onAuthenticationSuccess but nothing is writed in console.

I use sample explained in Capture successful login with AspectJ and Spring Security but it is not working.

Any idea ?

Thanks

Community
  • 1
  • 1
Jonathan Lebrun
  • 1,462
  • 3
  • 20
  • 42

1 Answers1

0

I found the solution !

I created a new SuccessHandler bean :

public class SecurityAuthenticationSuccessHandler extends
    SimpleUrlAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
    Authentication authentication) throws IOException, ServletException {

    super.onAuthenticationSuccess(request, response, authentication);
}

}

And second point is to add it as a bean in the config and set it in formLogin :

    @Bean
public SecurityAuthenticationSuccessHandler getSuccessHandler(){
    return new SecurityAuthenticationSuccessHandler();
}

http.authorizeRequests().antMatchers("/*").permitAll().and()
            .formLogin()
            .successHandler(successHandler)
            .permitAll().and().logout().permitAll();
Jonathan Lebrun
  • 1,462
  • 3
  • 20
  • 42