【问题标题】:ExecutorService with SecurityContextHolder带有 SecurityContextHolder 的 ExecutorService
【发布时间】:2020-04-30 18:56:49
【问题描述】:

我正在使用 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。

【问题讨论】:

    标签: java spring spring-security executorservice security-context


    【解决方案1】:

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

    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-06
      • 2019-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多