问题
Has anyone managed to get Spring Boot w/ Spring Security to handle AuthorizedEvent's (i.e. for audit log)?
I have implemented the following application event listener:
@Component
public class AuthorizationSuccessAudit implements ApplicationListener<AuthorizedEvent> {
private static Logger auditLogger = LoggerFactory.getLogger("audit");
@Override
public void onApplicationEvent(AuthorizedEvent event) {
auditLogger.info("Authorization granted to user: {} - {}", event.getAuthentication().getName(), event.getConfigAttributes());
}
}
and have a test MVC endpoint annotated with @PreAuthorize. I was expecting that the spring security grants would show up on the log. While this works for every other event I used (AuthenticationSuccessEvent, AuthenticationFailureEvent, AbstractAuthenticationFailureEvent) it does not for the AuthorizedEvent.
I tried browsing the Spring Boot source and it seems this event is not handled in AuthorizationAuditListener.java, is this possibly a bug or am I hacking at it the wrong way?
回答1:
As per spring boot documentation, Use Spring Boot Actuator (audit framework for Spring Boot), and provide your own implementations of AbstractAuthorizationAuditListener.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>1.3.0.RELEASE</version>
</dependency>
And something similar to this..
class TestAuthorizationAuditListener extends AbstractAuthorizationAuditListener {
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
}
@Override
public void onApplicationEvent(AbstractAuthorizationEvent event) {
}
}
回答2:
It looks like spring boot can not realize that here you want to handle event.
Try to annotate method so that spring knows that here you want to handle event
@EventListener(value = {AuthorizedEvent.class})
public void onApplicationEvent(AuthorizedEvent event) {
auditLogger.info("Authorization granted to user: {} - {}", event.getAuthentication().getName(), event.getConfigAttributes());
}
来源:https://stackoverflow.com/questions/35426100/spring-boot-spring-security-authorization-success-audit