Spring Boot + Spring Security authorization success audit

泄露秘密 提交于 2019-12-10 18:47:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!