Java Future - Spring Authentication在AuditorAware中为null [英] Java Future - Spring Authentication is null into AuditorAware
问题描述
这是我的方案:
我的应用启用了Mongo审核,使用自定义AuditorAware从 SecurityContext获取当前用户
。这适用于同步方法,并且当前审核员已成功保存,但我无法使用 @Async
方法使其正常工作。
My app has Mongo Auditing enabled, with a custom AuditorAware which gets the current user from the SecurityContext
. This works well with synchronous methods, and the current auditor is successfully saved, but I can't make it work properly with @Async
methods.
我有一个异步方法( CompletableFuture
),它对我的Mongo数据库进行了一些更新。当调用 AuditorAware.getCurrentAuditor()
时,不存在任何身份验证信息,我无法获得当前的审计员( SecurityContextHolder.getContext()。 getAuthentication()
返回 null
)。
I have an async method (CompletableFuture
) that makes some updates on my Mongo Database. When the AuditorAware.getCurrentAuditor()
is called, no authentication info exists, and I can't get the current auditor (SecurityContextHolder.getContext().getAuthentication()
returns null
).
@Override
public User getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()
|| authentication instanceof AnonymousAuthenticationToken) {
log.error("Not authenticated");
return null;
}
[...]
}
我正在使用 DelegatingSecurityContextAsyncTaskExecutor
:
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(20);
executor.setMaxPoolSize(100);
executor.setQueueCapacity(200);
executor.initialize();
return new DelegatingSecurityContextAsyncTaskExecutor(executor);
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new ItacaExceptionHandler();
}
}
如何让它正常工作?
推荐答案
Spring安全上下文始终绑定到Threadlocal。
Spring security context is always bound to Threadlocal.
可以为安全上下文另外设置MODE_INHERITABLETHREADLOCAL。
Probabably you may to additionally set MODE_INHERITABLETHREADLOCAL for the security context.
@Bean
public MethodInvokingFactoryBean methodInvokingFactoryBean() {
MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
methodInvokingFactoryBean.setTargetClass(SecurityContextHolder.class);
methodInvokingFactoryBean.setTargetMethod("setStrategyName");
methodInvokingFactoryBean.setArguments(new String[]{SecurityContextHolder.MODE_INHERITABLETHREADLOCAL});
return methodInvokingFactoryBean;
}
http://www.ogrigas.eu/spring/2010/04/inherit-spring-security-context-在子线程
如何设置Spring Security SecurityContextHolder策略?
这篇关于Java Future - Spring Authentication在AuditorAware中为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!