Last active
February 2, 2022 03:57
-
-
Save twaddington/8358b13f6931359f4e200222d2fa7727 to your computer and use it in GitHub Desktop.
This code demonstrates a method of signing OkHttp requests with an OAuth access token. An Authenticator is provided to renew an expired token using a refresh token.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Copyright (C) 2017 Tristan Waddington <[email protected]> | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in | |
all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
THE SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright (C) 2017 Tristan Waddington <[email protected]> | |
* | |
* This software may be modified and distributed under the terms | |
* of the MIT license. See the LICENSE file for details. | |
*/ | |
data class TokenAuth( | |
val accessToken: String, | |
val refreshToken: String, | |
val expiresIn: Long, | |
val expiresAt: Instant = Instant.now().plusSeconds(expiresIn) | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright (C) 2017 Tristan Waddington <[email protected]> | |
* | |
* This software may be modified and distributed under the terms | |
* of the MIT license. See the LICENSE file for details. | |
*/ | |
import okhttp3.Authenticator | |
import okhttp3.Request | |
import okhttp3.Response | |
import okhttp3.Route | |
import retrofit2.Call | |
import retrofit2.http.Body | |
import retrofit2.http.POST | |
import java.io.IOException | |
interface AuthProviderApi { | |
@POST("/oauth/renew") | |
fun renew(@Body req: RenewRequest): Call<RenewResponse> | |
} | |
data class RenewRequest( | |
val refresh_token: String, | |
val grant_type: String = "refresh_token" | |
) | |
data class RenewResponse( | |
val access_token: String, | |
val expires_in: Long, | |
val expires_at: Instant = Instant.now().plusSeconds(expires_in) | |
) | |
class TokenAuthenticator( | |
private val store: TokenStore, | |
private val service: AuthProviderApi | |
) : Authenticator { | |
override fun authenticate(route: Route, response: Response): Request? { | |
if (response.code() != 401) return null | |
val tokens = store.getTokens() ?: return null | |
synchronized(this) { | |
val request = response.request() | |
// Validate that the tokens were not mutated by another thread | |
if (tokens != store.getTokens()) { | |
val accessToken = store.getTokens()?.accessToken ?: "" | |
// Tokens have been mutated, retry request with updated auth | |
if (!accessToken.isEmpty()) return request.withAuthorization(accessToken) | |
} | |
// Request fresh access token | |
try { | |
val renewRequest = RenewRequest(tokens.refreshToken) | |
val renewResponse = service.renew(renewRequest).execute() | |
val body = renewResponse.body() | |
if (renewResponse.isSuccessful && body != null) { | |
val newToken = body.access_token | |
val usedToken = response.request().getAuthorizationToken() | |
if (newToken != usedToken) { | |
store.setTokens(tokens.copy( | |
accessToken = newToken, | |
expiresAt = body.expires_at, | |
expiresIn = body.expiresIn)) | |
return request.withAuthorization(newToken) | |
} | |
} | |
} catch (e: IOException) { | |
// todo: Log the exception | |
} | |
} | |
return null | |
} | |
} | |
internal fun Request.withAuthorization(accessToken: String) = | |
this.newBuilder() | |
.header("Authorization", "Bearer $accessToken") | |
.build() | |
internal fun Request.getAuthorizationToken(): String? = | |
this.header("Authorization") | |
?.replace("Bearer", "") | |
?.trim() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright (C) 2017 Tristan Waddington <[email protected]> | |
* | |
* This software may be modified and distributed under the terms | |
* of the MIT license. See the LICENSE file for details. | |
*/ | |
import okhttp3.Interceptor | |
import okhttp3.Interceptor.Chain | |
import okhttp3.Response | |
class TokenAuthInterceptor(private val store: TokenStore) : Interceptor { | |
override fun intercept(chain: Chain): Response { | |
val tokens = store.getTokens() ?: return chain.proceed(chain.request()) | |
val req = chain.request().newBuilder() | |
.header("Authorization", "Bearer ${tokens.accessToken}") | |
.build() | |
return chain.proceed(req) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright (C) 2017 Tristan Waddington <[email protected]> | |
* | |
* This software may be modified and distributed under the terms | |
* of the MIT license. See the LICENSE file for details. | |
*/ | |
interface TokenStore { | |
fun hasTokens(): Boolean | |
fun getTokens(): TokenAuth? | |
fun setTokens(tokens: TokenAuth) | |
fun clear() | |
fun isExpired() = getTokens()?.expiresAt?.isBefore(Instant.now()) ?: true | |
fun isNotExpired() = !isExpired() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment