How to implement AuditorAware with Spring Data JPA and Spring Security?

前端 未结 4 1566
星月不相逢
星月不相逢 2021-02-01 19:29

We use Hibernate/JPA, Spring, Spring Data and Spring Security in our application. I have a standard User entity which is mapped using JPA. Further, I have a U

4条回答
  •  深忆病人
    2021-02-01 19:58

    To be honest, You do not actually require one another entity. For example, I had similar problem and I resolved it in following way:

    public class SpringSecurityAuditorAware implements AuditorAware, ApplicationListener {
        private static final Logger LOGGER = getLogger(SpringSecurityAuditorAware.class);
        @Autowired
        SUserRepository repository;
        private SUser systemUser;
    
        @Override
        public SUser getCurrentAuditor() {
            final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            SUser principal;
            if (authentication == null || !authentication.isAuthenticated()) {
                principal = systemUser;
            } else {
                principal = (SUser) authentication.getPrincipal();
            }
            LOGGER.info(String.format("Current auditor is >>> %s", principal));
            return principal;
        }
    
        @Override
        public void onApplicationEvent(final ContextRefreshedEvent event) {
            if (this.systemUser == null) {
                LOGGER.info("%s >>> loading system user");
                systemUser = this.repository.findOne(QSUser.sUser.credentials.login.eq("SYSTEM"));
            }
        }
    }
    

    Where SUser is both the class which I use for auditing as well as for the security. I had maybe different use case than Yours and my approach will be deleted after, but it can be resolved like this.

提交回复
热议问题