如何在Spring中调用Callable中的当前用户

问题描述 投票:1回答:2

我需要让当前用户在Callable执行的函数内部。用于执行回调的方法:

public static boolean run(List<Callable<Integer>> callables) {
    try {
        ExecutorService executor = Executors.newWorkStealingPool();
        long startTime = System.currentTimeMillis();
        executor.invokeAll(callables);
        long stopTime = System.currentTimeMillis();
        long elapsedTime = stopTime - startTime;
        return true;
    }
    catch (InterruptedException e) {
        e.printStackTrace();
        return false;
    }
}

在callable里面我调用一个需要获取当前用户的函数,我尝试使用SecurityContextHolder:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
System.out.println("auth" + auth);

但这显示我无效。

请帮忙。谢谢。

spring spring-boot spring-security callable
2个回答
2
投票

SecurityContextHolder(默认情况下)通过ThreadLocal存储SecurityContext。它仅在处理请求的线程中可用。

您必须获取SecurityContext(在请求线程上)并在执行它们之前将其传递给每个Callable。


1
投票

Matt是正确的RE:Spring将身份验证存储在线程局部变量中。您可以将Spring Security配置为将安全上下文从父线程传递到通过调用生成的安全上下文:

SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);

https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/core/context/SecurityContextHolder.html

© www.soinside.com 2019 - 2024. All rights reserved.