Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add audit for logout with Jhipster generated code?

I debugged how audit is getting added into system for successful login and figured out that CustomAuditEventRepository.auditEventRepository().add(AuditEvent event) is getting invoked using aop. Is there any documentation how to add audits for any custom actions?

like image 658
raok1997 Avatar asked Mar 04 '15 11:03

raok1997


1 Answers

I was able to achieve the above thing with the following code.

  • Created class that could publish audit event.
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));
    }
}
  • Inject AuditEventPublisher where you need it and call publish with audit event to be inserted to 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();
    }

}
like image 77
raok1997 Avatar answered Nov 07 '22 17:11

raok1997