【问题标题】:get current user in service layer获取服务层的当前用户
【发布时间】:2015-09-12 01:41:05
【问题描述】:

我想在服务层获取当前用户

我尝试了以下代码,但出现空指针异常

@Service
public class MyService{

@Autowired
TodoRepository todoRepository;

public void execute(){
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    Todo todo = new Todo();
    todo.setDomain(auth.getName());
    todoRepository.save(todo);  
} 

谁能告诉我如何通过服务层中的spring security获取登录用户?

【问题讨论】:

  • 从哪里得到空指针异常?理论上,如果您的设置有问题,它永远不应该为 null。
  • 你总是从web层调用服务层吗? SecurityContext 基于线程范围(请求)工作。如果您启动一些异步方法,则会失败,因为它将是另一个线程。

标签: java spring spring-mvc spring-security


【解决方案1】:

这将帮助您找到当前经过身份验证的用户:

 @Override
    public Person getCurrentlyAuthenticatedUser() {

        Authentication authentication = SecurityContextHolder.getContext()
                                            .getAuthentication();

        if (authentication == null) {
            return null;
        } else {
            // The line below calls the method from my Person database, 
            // where I search users by their Email(username)
            return personDAO.findPersonByUsername(authentication.getName());
        }
    }

希望这会有所帮助。如果没有,请告诉我,我将删除我的答案。

【讨论】:

  • 这不起作用,因为 SecurityContextHolder.getContext().getAuthentication() 得到 null
  • 表示当前没有登录用户或您的 Spring-security 设置不正确。我在生产中使用该方法超过 6 个月。
  • 这在控制器层工作正常,但在服务层得到空异常
  • 使用导入和注释完全粘贴您的服务层。无需粘贴方法的内容。还要粘贴错误日志以及在哪一行出现错误。请编辑您的主要帖子以执行此操作。如果你有 ApplicationContext.xml 和 securityAppplication.xml,也粘贴它们。不可能盲目地猜测可能是什么问题。
猜你喜欢
  • 2015-02-22
  • 2018-06-16
  • 2019-01-12
  • 1970-01-01
  • 2021-12-04
  • 2020-11-23
  • 1970-01-01
  • 2019-01-12
  • 1970-01-01
相关资源
最近更新 更多