如何使用Jhipster生成的代码添加用于注销的审核?

时间:2015-03-04 11:24:43

标签: spring jhipster audit-logging

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

1 个答案:

答案 0 :(得分:10)

我能用以下代码实现上述功能。

  • 创建可以发布审核事件的类。
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并调用publish以及要插入到db的审计事件
@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();
    }

}