我需要让当前用户在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);
但这显示我无效。
请帮忙。谢谢。
SecurityContextHolder(默认情况下)通过ThreadLocal存储SecurityContext。它仅在处理请求的线程中可用。
您必须获取SecurityContext(在请求线程上)并在执行它们之前将其传递给每个Callable。
Matt是正确的RE:Spring将身份验证存储在线程局部变量中。您可以将Spring Security配置为将安全上下文从父线程传递到通过调用生成的安全上下文:
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);