当前位置: 首页 > 面试题库 >

Spring Security and @Async (Authenticated Users mixed up)

于捷
2023-03-14
问题内容

我使用@Async与Spring异步调用该方法。该方法调用其他以Spring Security Annotation @PreAuthorize注释的方法。为了使授权有效,我必须将SecurityContextHoldermode 设置为MODE_INHERITABLETHREADLOCAL,以便将身份验证信息传递到异步调用。到目前为止一切正常。

但是,当我注销并以其他用户身份登录时,在异步方法SecurityContextHolder中存储了已注销的旧用户的身份验证信息。当然,这会导致意外的AccessDenied异常。同步调用没有这种问题。

我已经定义了<task:executor id="executors" pool-size="10"/>,所以一旦执行程序池中的线程已初始化,就不会覆盖身份验证信息,这可能是一个问题吗?


问题答案:

我猜想MODE_INHERITABLETHREADLOCAL线程池不能正常工作。

作为一种可能的解决方案,你可以尝试继承ThreadPoolTaskExecutor并覆盖其方法以进行SecurityContext手动传播,然后声明该executor而不是<task:executor>,如下所示:

public void execute(final Runnable r) {
    final Authentication a = SecurityContextHolder.getContext().getAuthentication();

    super.execute(new Runnable() {
        public void run() {
            try {
                SecurityContext ctx = SecurityContextHolder.createEmptyContext();
                ctx.setAuthentication(a);
                SecurityContextHolder.setContext(ctx);
                r.run();
            } finally {
                SecurityContextHolder.clearContext();
            }
        }
    });
}


 类似资料:
  • async()函数是一个简单任务的”启动”(launcher)函数,它是本FAQ中唯一一个尚未在标准草案中投票通过的特性。我希望它能在调和两个略微不同的意见之后最终于10月份获得通过(记得随时骚扰你那边的投票委员,一定要为它投票啊?)。 下边是一种优于传统的线程+锁的并发编程方法示例(译注:山寨map-reduce哦): template<class T,class V> struct Accum

  • asynchronous operation在线程中执行,与main应用程序线程分开。 当应用程序调用方法异步执行操作时,应用程序可以在异步方法执行其任务时继续执行。 例子 (Example) 让我们举个例子来理解这个概念。 这里,程序使用IO library接受用户输入。 import 'dart:io'; void main() { print("Enter your name :"

  • Throws an exception. Asynchronous iteration over object-like sequences is not supported. Examples Lazy({ foo: 'bar' }).async() // throws

  • Creates a sequence, with the same elements as this one, that will be iterated over asynchronously when calling each. Signature Sequence.async = function(interval) { /*...*/ } Sequence.async = function

  • This plugin allows to easily code very long-lasting loops in an asynchronous way to avoid losing the browser responsiveness.

  • Async/await 是以更舒适的方式使用 promise 的一种特殊语法,同时它也非常易于理解和使用。 Async function 让我们以 async 这个关键字开始。它可以被放置在一个函数前面,如下所示: async function f() { return 1; } 在函数前面的 “async” 这个单词表达了一个简单的事情:即这个函数总是返回一个 promise。其他值将自动被

  • Async patterns to your Flutter application. See more widgets in the widget catalog. FutureBuilder Widget that builds itself based on the latest snapshot of interaction with a Future.Documentation Stre

  • 在第一章节,我们简要介绍了async/.await,并用它来构建一个简单的服务器。本章将更为详细讨论async/.await的它如何工作以及如何async代码与传统的 Rust 程序不同。 async/.await是 Rust 语法的特殊部分,它使得可以 yield 对当前线程的控制而不是阻塞,从而允许在等待操作完成时,其他代码可以运行。 async有两种主要的使用方式:async fn和asyn