8

我调试了如何将审计添加到系统中以成功登录,并发现CustomAuditEventRepository.auditEventRepository().add(AuditEvent event)正在使用aop调用。是否有任何文档如何为任何自定义操作添加审核?

4

1 回答 1

11

我能够使用以下代码实现上述目标。

  • 创建了可以发布审计事件的类。
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.boot.actuate.audit.listener.AuditApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AuditEventPublisher implements ApplicationEventPublisherAware  {
    private ApplicationEventPublisher publisher;

    @Override
    public void setApplicationEventPublisher(
            ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }

    public void publish(AuditEvent event) {
        if (this.publisher != null)
            this.publisher.publishEvent(new AuditApplicationEvent(event));
    }
}
  • 在需要的地方注入 AuditEventPublisher 并调用带有审计事件的发布以插入到数据库
@RestController
@RequestMapping("/api")
public class UserXAuthTokenController {

    @Inject
    private AuditEventPublisher auditPublisher;

.....
.....

    @RequestMapping(value = "/logout",
            method = RequestMethod.POST)
    @Timed
    public void logout(@RequestParam String authToken) {
        String principal = tokenProvider.getUserNameFromToken(authToken);
        AuditEvent event = new AuditEvent(principal, "LOGOUT_START", new HashMap<String, Object>());
        auditPublisher.publish(event);
        SecurityContextHolder.clearContext();
    }

}
于 2015-03-05T14:20:10.247 回答