After authenticate the user using authorization url, I’m obtaining refresh token and access token using following method in my Android project(Kotlin).
private suspend fun exchangeCodeForToken(code: String): JSONObject? {
return withContext(Dispatchers.IO) {
val form = FormBody.Builder()
.add("grant_type", "authorization_code")
.add("code", code)
.add("client_id", CLIENT_ID)
.add("client_secret", CLIENT_SECRET)
.build()
val req = Request.Builder()
.url(TOKEN_URL)
.post(form)
.build()
httpClient.newCall(req).execute().use { resp ->
val body = resp.body?.string()
if (resp.isSuccessful && body != null) {
JSONObject(body)
} else {
Timber.e("Token exchange failed: ${resp.code} - $body")
null
}
}
}
}
Now I’m getting the user information and it is working fine. But after the access token is expired(1 hour), I’m trying to refresh it using the refresh token but I’m getting the error (refresh token expired).
private suspend fun refreshAccessToken(): Boolean {
return withContext(Dispatchers.IO) {
val refresh = getStoredRefreshToken() ?: return@withContext false
val form = FormBody.Builder()
.add("grant_type", "refresh_token")
.add("refresh_token", refresh)
.add("client_id", CLIENT_ID)
.add("client_secret", CLIENT_SECRET)
.build()
val req = Request.Builder()
.url(TOKEN_URL)
.post(form)
.build()
httpClient.newCall(req).execute().use { resp ->
val body = resp.body?.string()
if (resp.isSuccessful && body != null) {
val json = JSONObject(body)
val accessToken = json.optString("access_token")
val refreshToken = json.optString("refresh_token")
if (accessToken.isNotEmpty()) {
saveAccessTokenLocally(accessToken)
saveRefreshTokenLocally(refreshToken)
_uiState.value = _uiState.value.copy(accessToken = accessToken)
return@withContext true
}
}
Timber.e("Refresh token failed: ${resp.code} - $body")
return@withContext false
}
}
}
Error message: “Refresh token failed: 400 - {"error":"invalid_grant","error_description":"Refresh token has expired"}”
I know refresh token can be used only once, and this is the only time I’m using the refresh token, so it was not used before.
I got the same error with Box Java SDK, so I tried using the REST APIs, but the same result.
Can any one help me with this?