Search code examples
androidfacebookgoogle-oauthretrofitokhttp

Handling third party logins with okhttp's Authenticator interface


When I was searching on how to handle a 401 response from API, I came across https://github.com/square/okhttp/wiki/Recipes#handling-authentication. I am posting here to know the best approach to handle third party authentication like Google/Facebook using this interface. According to the example, we make a synchronous call and get the new token from the API server. But, when the user is authenticated via G+/FB we may have to make multiple calls which are not synchronous

This example is based on my understanding on how to re authenticate a Google user to your app. I would make a call to GoogleSignInApi.silentSignIn(), which is a async call to get the ServerAuthCode/IDtoken. This would be sent to my API server for verification and a new token will be provided to my android application. If the user has revoked permission on Google's app security portal, I have to call the intent to show the consent and accept page. After user's acceptance I either get a new token from google or I need to cancel the token generation process. Same steps applies to FB as well

Since the above process is async how can I use Authenticator interface in this situation?


Solution

  • I would suggest splitting these into two distinct flows

    1. Verify token at startup and send through the auth flow if needed
    2. Use an Interceptor, not Authenticator, since it will allow you to set the token in the initial request instead of waiting for the 4xx response.

    I do something similar with a desktop okhttp client project of mine e.g.

    1. https://github.com/yschimke/oksocial/blob/release/1.0.57/src/main/java/com/baulsupp/oksocial/services/facebook/FacebookAuthFlow.java
    2. https://github.com/yschimke/oksocial/blob/release/1.0.57/src/main/java/com/baulsupp/oksocial/services/facebook/FacebookAuthInterceptor.java