如何使用Spring Aspect记录SavedRequestAwareAuthenticationSuccessHandler.onAuthenticationSuccess?

时间:2014-01-21 11:05:54

标签: spring spring-security spring-aop

我尝试使用Spring Security成功登录用户时进行记录。我使用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");
}
}

方法运行正常但记录两次。我尝试使用onAuthenticationSuccess,但在控制台中没有任何内容。

我使用Capture successful login with AspectJ and Spring Security中解释的样本,但它无效。

有什么想法吗?

谢谢

1 个答案:

答案 0 :(得分:0)

我找到了解决方案!

我创建了一个新的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);
}

}

第二点是在配置中将其添加为bean并将其设置为formLogin:

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

http.authorizeRequests().antMatchers("/*").permitAll().and()
            .formLogin()
            .successHandler(successHandler)
            .permitAll().and().logout().permitAll();