【问题标题】:spring security current user in thread线程中的弹簧安全当前用户
【发布时间】: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


【解决方案1】:

您可以将 SecurityContext 从一个线程转移到另一个线程

Runnable originalRunnable = new Runnable() {
public void run() {
    // invoke secured service
}
};
SecurityContext context = SecurityContextHolder.getContext();
DelegatingSecurityContextRunnable wrappedRunnable =
    new DelegatingSecurityContextRunnable(originalRunnable, context);

new Thread(wrappedRunnable).start();

查看并发支持

https://docs.spring.io/spring-security/reference/features/integrations/concurrency.html

【讨论】:

    【解决方案2】:

    如果希望衍生线程继承父线程的SecurityContext,则应设置MODE_INHERITABLETHREADLOCAL策略。

    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL)

    有一个issue,当它与线程池一起使用时。这似乎已解决。

    【讨论】:

    • @JinuPC 我已经删除了损坏的链接并添加了代码。
    【解决方案3】:

    如果您希望所有子线程从ThreadLocal 继承SecurityContextHolder,您可以使用带有@PostConstruct 注释的方法来全局设置它。现在您的子线程将可以访问相同的 SecurityContextHolder。

    @PostConstruct
    void setGlobalSecurityContext() {
      SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
    }
    

    干杯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-03
      • 2018-09-08
      • 1970-01-01
      相关资源
      最近更新 更多