带有 SecurityContextHolder 的 ExecutorService

ExecutorService with SecurityContextHolder

我正在通过使用 ExecutorService 将方法的单线程执行更改为多线程执行。 它在内部调用 SecurityContextHolder,抛出异常:

原因:java.lang.Exception:在安全上下文中找不到身份验证对象。 在 com.LoggedInUser.getLoggedInUser(LoggedInUser.java:25) 在 com.Controller.submitRate(RateController.java:242)

我的代码:

method(){

Future<Results> future = executor.submit(new callableClass(form, request));

            if (null != future.get()) {
                rates = future.get();
            }}
}


class callableClass implements Callable<RateResults> {

    private Form form;
    private HttpServletRequest request;

    public RateShippmentCaller(Form form, HttpServletRequest request) {
        super();
        this.form = form;
        this.request = request;
    }

    @Override
    public Results call() throws Exception {
        return controller.submit(form, request);
    }

}

submit(form, request){
LoggedInUser.getLoggedInUser()
}

class LoggedInUser{
    getLoggedInUser(){
       SecurityContext **secCtx** = SecurityContextHolder.getContext();
        Authentication authentication = secCtx.getAuthentication();
        if (authentication == null) {
            throw new Exception("Authentication object not found in security context.");
        }
    }
}

请告诉我如何避免异常。 secCtx 正在返回 null。

尝试设置以下安全上下文持有者策略:

SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);

注意你不应该使用它,因为你有一个线程池,只有每次都创建一个新线程。

另一种传输上下文的方式:

Runnable runnable = new Runnable() {
    public void run() {
        // you’ll be able to access the context here
    }
};
SecurityContext context = SecurityContextHolder.getContext();
DelegatingSecurityContextRunnable wrappedRunnable =
    new DelegatingSecurityContextRunnable(runnable, context);

new Thread(wrappedRunnable).start();