Hibernate envers spring web app how to log username

半城伤御伤魂 提交于 2019-12-12 18:50:44

问题


I am using hiberbate 3.5 and spring 3.x

I have envers working and the ... _aud and revinfo record are now being written.

I now need to add the username to the audit record I'm guessing revinfo is the best place I have seen an example for seam app but nothing for spring app in jboss

Can anyone help with this please.

My main aim is to be able to record the windows authenticated user.


回答1:


The Envers documentation has an answer for this if you use Seam.

public class ExampleListener implements RevisionListener {
    public void newRevision(Object revisionEntity) {
        ExampleRevEntity exampleRevEntity = (ExampleRevEntity) revisionEntity;
        Identity identity = (Identity) Component.getInstance("org.jboss.seam.security.identity");

        exampleRevEntity.setUsername(identity.getUsername());
    }
}

So, I suppose your question would be how to retrieve the currently logged in user at that point if you don't use Seam? I'm sure there are several ways to do it, we do it like this.

  • Write a ServletFilter
  • In the filter get the principal from the session (or the security context if you use a security framework like Spring Security)
  • Store it in the log4j MDC

Code example from filter

protected void beforeRequest(final HttpServletRequest request, final String message) {
  final Principal principal = request.getUserPrincipal();
  final String username = principal != null ? principal.getName() : null;
  if (username != null) {
    MDC.put(USER, username);
  }
}
protected void afterRequest(final HttpServletRequest request, final String message) {
  MDC.remove(USER);
}

Later you can get the user from anywhere in your code because the MDC has a static get(String) method.



来源:https://stackoverflow.com/questions/14130922/hibernate-envers-spring-web-app-how-to-log-username

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