这是我的情景:
我的应用程序启用了Mongo审核,使用自定义AuditorAware从SecurityContext获取当前用户.这适用于同步方法,并且成功保存了当前审计员,但我无法使用@Async方法使其正常工作.
我有一个异步方法(CompletableFuture),它在我的Mongo数据库上进行了一些更新.调用AuditorAware.getCurrentAuditor()时,不存在身份验证信息,我无法获取当前审计员(SecurityContextHolder.getContext().getAuthentication()返回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.
也可以为安全上下文另外设置MODE_INHERITABLETHREADLOCAL.
@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-in-child-threads
How to set up Spring Security SecurityContextHolder strategy?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。