Cal*_*ity 6 android oauth-2.0 appauth
我遇到的问题与提出此问题的用户基本相同:Android 的 AppAuth 库缺乏适当的文档。
My problem occurs when the current access token expires, disallowing API communication from inside my app. To prevent that I forced my TokenInterceptor to acquire the token on each request from the getAccessToken method, which uses AppAuth's performActionWithFreshTokens method, that supposedly performs a token refresh request (I looked through its code). However, it always throws an AuthorizationException with error invalid_grant for me.
It crashes my app the first time, but works fine after relaunching. So the token does refresh, doesn't it?
class TokenInterceptor @Inject constructor(
private val authStateStorage: AuthStateStorage,
private val authService: AuthorizationService
): Interceptor {
private companion object {
const val TAG = "TokenInterceptor"
const val AUTH_HEADER = "Authorization"
}
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
request.header(AUTH_HEADER) ?: run {
request = chain.request()
.newBuilder()
.addHeader(AUTH_HEADER, "Bearer ${getAccessToken()}")
.build()
}
return chain.proceed(request)
}
private fun getAccessToken(): String = runBlocking {
val authState = authStateStorage.authStateFlow.first()
val isNeedToUpdateToken = authState.needsTokenRefresh
// authState.refreshToken is not null or empty for me!
suspendCoroutine { continuation ->
authState.performActionWithFreshTokens(authService) { accessToken, _, exception ->
exception?.let {
Log.e(TAG, "Exception in token process: ", it)
continuation.resumeWithException(it)
} ?: run {
if (isNeedToUpdateToken) {
runBlocking {
authStateStorage.updateAuthState(authState)
}
}
continuation.resume(accessToken!!)
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Did I forget some steps for this to work properly? Why does it throw an exception, but I still wind up with a valid token?
invalid_grant当刷新令牌过期时,通常发生在刷新令牌授予消息中。首先检查您的授权服务器是否确实向应用程序返回了刷新令牌,并且其过期时间是否配置为大于访问令牌的过期时间。
就我个人而言,我喜欢控制自己的 API 调用,而不是通过 AppAuth 来完成所有这些调用,因此我performTokenRequest直接使用该方法。以下是一些您可能会发现有助于比较的示例代码:
为了最好地进行故障排除,我建议还跟踪 HTTP 请求以查看刷新令牌授予消息,这应该类似于我的博客文章中的步骤 15。那里还有一个工作示例,以防万一有用。
| 归档时间: |
|
| 查看次数: |
2508 次 |
| 最近记录: |