Spring Boot RabbitMQ MessageLog使用Sping Boot 返回空上下文

368yc8dk  于 4个月前  发布在  Spring
关注(0)|答案(1)|浏览(57)

我正在使用MessageListener实现从RabbitMQ接收消息,但securityContextHolder.getContext()只在onMessage中返回null,但它对应用程序的其余部分工作正常:

@Override
public void onMessage(Message message) {
    Gson gson = new Gson();
    ControleResult resultControle = gson.fromJson(new String(message.getBody()), Facture.class);
    Optional<Facture> optional = dossierDao.findById(resultControle.getId());
    Facture facture= null;
    if (optional.isPresent()) {
        facture= optional.get();
    }
  
    factureDao.save(facture);
    log.info("USER     " + getLoggedInUserName());   
}

private String getLoggedInUserName() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.isAuthenticated()) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            ConnectedUser userDetails = (ConnectedUser) authentication.getPrincipal();

            return String.format("%s %s",userDetails.getUsername(), userDetails.getUserlastname());
        }
    }
    return null; 
}

字符串

eh57zj3b

eh57zj3b1#

SecurityContextHolder.getContext()默认使用ThreadLocal变量来存储Authentication对象。
当RabbitMQ监听器调用onMessage()函数时,它将在一个新的线程中调用。每个新的Thread将获得自己的ThreadLocal变量示例,因此命名为Thread“local”。这意味着它在Web应用程序中没有当前登录用户的上下文。
有关不同安全上下文保持器策略的更多信息,请参阅我对this问题的回答。

相关问题