我尝试在访问令牌过期时向服务器发送刷新令牌并接收新的访问令牌,但代码无法正常工作。
刷新令牌类
class RefreshToken(): Authenticator {
override fun authenticate(route: Route?, responsee: Response): Request? {
if (responsee.code == 401) {
lateinit var loginRepository: LoginRepository
lateinit var bodyRefresh: BodyRefresh
lateinit var access: StoreAccess //datastore for save token
lateinit var newAccess: String
CoroutineScope(Dispatchers.Main).launch {
access.getUserRefresh().collect {
val refresh = it.toString()
bodyRefresh.refresh = refresh
val response = loginRepository.RefreshAccess(bodyRefresh)
if (response.isSuccessful) {
access.saveUserRefresh(response.body()?.access.toString())
newAccess = response.body()?.access.toString()
}
}
}
return responsee.request.newBuilder().header("Authorization", "Bearer $newAccess.toString()")
.build()
} else {
return responsee.request
}
}
}
API服务
@POST("token/refresh/")
suspend fun refreshAcssec(@Body refresh: BodyRefresh): Response<ResponseAcces>
2条答案
按热度按时间qco9c6ql1#
我正在使用runBlocking{ }而不是CoroutineScope(Dispatchers.Main). launch。它对我很有效,但我不知道这是否是最好的解决方案
vc6uscn92#
我想这是可以的,因为Authenticator和Interceptor将在另一个线程上运行
检查此
enter link description here