我尝试从应用程序Spring的Spring上下文中获取用户,如下所示:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
问题是这些方法是异步的,注解@Async:
@Service
@Transactional
public class FooServiceImpl implements FooService {
@Async("asyncExecutor")
public void fooMethod(String bar) {
System.out.println("Foo: " + bar);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
}
}
问题是异步方法在另一个上下文中的另一个线程中运行。我尝试使用SecurityContextDelegationAsyncTaskExecutor
。用户被传播到异步方法,但如果我注销,异步方法中的用户为空。这是我的代码:
@Configuration
@EnableAsync
public class SpringAsyncConfig implements AsyncConfigurer {
@Override
@Bean(name = "asyncExecutor")
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setMaxPoolSize(1);
executor.setThreadGroupName("MyCustomExecutor");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setBeanName("asyncExecutor");
executor.initialize();
return new DelegatingSecurityContextAsyncTaskExecutor(executor);
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new CustomAsyncExceptionHandler();
}
}
我也使用了一个ThreadPoolTaskExecutor
,并使用“MODE_INHERITABLETHREADLOCAL”设置了Spring安全的上下文。但结果是一样的。如果我登录到应用程序,则用户不是null。如果我没有登录,则用户是null。我真正希望的是运行该方法的用户,而不是当前登录的用户。我的代码:
@Configuration
@EnableAsync
public class SpringAsyncConfig implements AsyncConfigurer {
@Override
@Bean(name = "asyncExecutor")
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setMaxPoolSize(1);
executor.setThreadGroupName("MyCustomExecutor");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setBeanName("asyncExecutor");
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new CustomAsyncExceptionHandler();
}
}
@Configuration
@ComponentScan(basePackageClasses = Application.class, includeFilters = @Filter({Controller.class}), useDefaultFilters = true)
public class MvcConfiguration extends WebMvcConfigurationSupport {
//others beans
@Bean
public MethodInvokingFactoryBean methodInvokingFactoryBean() {
MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
methodInvokingFactoryBean.setTargetClass(SecurityContextHolder.class);
methodInvokingFactoryBean.setTargetMethod("setStrategyName");
methodInvokingFactoryBean.setArguments(new String[]{SecurityContextHolder.MODE_INHERITABLETHREADLOCAL});
return methodInvokingFactoryBean;
}
}
最后,我找到了这个post。我尝试用一个CustomThreadPoolTaskExecutor覆盖execute方法。但是这个方法从来没有运行过。运行的ThreadPoolTaskExecutor方法是:
<T> Future<T> submit(Callable<T> task)
我的代码:
@Configuration
@EnableAsync
public class SpringAsyncConfig implements AsyncConfigurer {
@Override
@Bean(name = "asyncExecutor")
public Executor getAsyncExecutor() {
CustomThreadPoolTaskExecutor executor = new CustomThreadPoolTaskExecutor();
executor.setMaxPoolSize(1);
executor.setThreadGroupName("MyCustomExecutor");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setBeanName("asyncExecutor");
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new CustomAsyncExceptionHandler();
}
}
public class CustomThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
private static final long serialVersionUID = 1L;
@Override
public void execute(final Runnable r) {
final Authentication a = SecurityContextHolder.getContext().getAuthentication();
super.execute(new Runnable() {
@Override
public void run() {
try {
SecurityContext ctx = SecurityContextHolder.createEmptyContext();
ctx.setAuthentication(a);
SecurityContextHolder.setContext(ctx);
r.run();
} finally {
SecurityContextHolder.clearContext();
}
}
});
}
}
我的自定义executes方法从未运行。我在自定义ThreadPoolTaskExecutor中做错了什么?获取运行异步方法的用户的其他方法。没有上下文的当前用户。
4条答案
按热度按时间kognpnkq1#
Spring支持使用传播的SecurityContext发送异步请求。从编程模型的Angular 来看,新功能看似简单。您可以通过在安全配置器类中设置安全上下文策略名称来访问异步方法中的用户信息:
p5fdfcr12#
也许这有助于调用execute-method(在我的例子中是有效的):
wqsoz72f3#
这是我的实现,我已经使用TaskDecorator在新线程中复制SecurityContext,新线程使用这个新SecurityContext运行,即使用户在异步任务执行期间注销。
执行器的Xml声明
这是安全上下文复制装饰器类
最后对异步模式下使用threadPoolTaskExecutor一些方法进行了注解
nwnhqdif4#
MODE_INHERITABLETHREADLOCAL
不应该使用,如果你有池线程(阅读更多here),这是如果你有现代的Sping Boot 应用程序与@EnableAsync
的情况。要在
@Async
方法中保留安全上下文并使用默认的Sping Boot 线程池,只需在AsyncConfigurer
中定义DelegatingSecurityContextAsyncTaskExecutor
: