【发布时间】:2017-07-09 13:25:46
【问题描述】:
嗨,我在线程范围内使用弹簧安全时遇到了一些问题
System.out.println(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
new Thread(() -> System.out.println(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId())).start();
这两行应该给我当前的用户 ID
第一行按预期工作
第二行给我 NullPointerException 因为没有当前用户它是空值
我发现了这个问题,因为我想将很多行保存到歌曲表中,并且它有 @CreatedBy 用户,这将在线程中询问当前用户并且将失败,因为这将为当前用户提供空值
【问题讨论】:
-
为什么要有一个单独的线程来获取当前用户?按照第一个选项中的建议进行操作。
-
默认情况下,Spring Security
Authentication对象基于每个Thread存储在ThreadLocal中。因此,使用new Thread触发一个新线程,然后尝试在该新线程中检索Authentication对象将返回null。 Spring Security 官方文档提供了multiple options,用于在多线程环境中工作。查看文档并选择适合您环境的策略。 -
为什么要使用单独的线程来获取当前用户¿ 因为我没有调用 get current user the createdby annotations 调用它,它在我创建的线程中调用它所以这由春天魔法
标签: spring multithreading spring-security