OkHttp & OAuth: Token Refreshes
Every time we log into an app using our Facebook or Google account, we rely on the authentication protocol OAuth.
As developers, we frequently have to work with APIs that use OAuth as their authentication mechanism. The Coinbase App uses OAuth to authenticate users so they can buy and sell digital currencies with the Coinbase API.
After receiving a token, apps typically persist it and apply it to each request that requires authentication. In the Coinbase Android app, we do this using an Interceptor
. Each request asks an AccessTokenProvider
for the token and tacks it onto its headers.
But what happens when our access token expires or gets revoked? Making a request with an invalid token results in a 401. Wouldn’t it be nice if our network stack could handle refreshing our token automatically and even retry failed requests for callers?
Enter OkHttp’s Authenticator API. Using a custom Authenticator we can build this behavior into OkHttp.
Now when building our OkHttpClient
we plug our Authenticator
in:
OkHttpClient.Builder()
.authenticator(AccessTokenAuthenticator(accessTokenProvider))
.build()
Eureka! Instead of having to retry 401s and perform refreshes in our application code, we’ve built this behavior into OkHttp for all our authenticated calls.
Special thanks to Tristan Waddington for being a sounding board for OAuth and OkHttp internals.
P.S. Coinbase is hiring!