gpt4 book ai didi

kotlin - 为什么在Kotlin异步方法中SecurityContextHolder.getContext()。authentication等于null?

转载 作者:行者123 更新时间:2023-12-02 13:34:53 24 4
gpt4 key购买 nike

我是Kotlin Coroutines的新手,我想以异步方式为我的每位员工调用API。但是我遇到了一个问题,即新协程的存在,我无法从SecurityContextHolder.getContext检索身份验证。

有人可以解释一下为什么Kotlin中的SecurityContextHolder.getContext().authentication块中的null等于GlobalScope.async{...}吗?新协程是否具有单独的安全性上下文?我该如何解决这个问题?我有一种方法可以避免将身份验证从调用的perform()函数传递给callApi()函数?

您可以在下面找到代码片段:

fun perform() {
// SecurityContextHolder.getContext().authentication contains some value!!!

val deferred = employeesRepository.getEmployees().map { callApi(it) }

runBlocking {
deferred.forEach { it.await() }
}

}

fun callApi(employee: EmployeeModel) = GlobalScope.async {
// SecurityContextHolder.getContext().authentication is null here!!!
}

最佳答案

如果我没记错的话,SecurityContextHolder.getContext()持有对身份验证对象的线程本地引用。实际上,您可以使用协程切换到另一个线程(该线程没有线程本地身份验证对象)。

我认为通过身份验证对象可以工作,当我开始阅读您的问题时,这也是我的第一个想法。为什么要避免这种情况?

也许您可以使用auth对象创建一个协程上下文(或者为此目的存在一个现有的上下文?),但这只是我的猜测,我还没有使用协程的真正经验。

编辑:
通过快速搜索,我发现了这一点。您可以在此线程中找到有趣的想法:
https://github.com/Kotlin/kotlinx.coroutines/issues/119

关于kotlin - 为什么在Kotlin异步方法中SecurityContextHolder.getContext()。authentication等于null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58500643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com