Search code examples
androidauthenticationoauthgoogle-plusfault-tolerance

Google+ Auth fault tolerance (code was already redeemed)


I'm currently implementing Google+ authentication on Android with offline access. This entails requesting a one-time authorization code that can be sent to the server and redeemed for a refresh token. So far so good.

However imagine that there is an error on the server between the time that the code is redeemed and a response is sent to the user indicating that they have been authenticated. If the user then re-requests an authentication code, Google returns the same one as was previously issued. When the server attempts to redeem this code with Google, the error

"Invalid Grant - This code was already redeemed"

is returned.

Is there a way of recovering gracefully from such a case that doesn't require the user to "try again later" when Google will decide to issue a new code? I realise that the waiting period to get a new code is only 5 or 10 minutes, but this still isn't a very nice situation from the user's point of view.


Solution

  • What you need to use is clearToken(Context context, String token).

    If you get the response:

    "Invalid Grant - This code was already redeemed"

    You need to pass the authentication code you used to the clearToken() function. This removes that token from the cache.

    Call getToken() again and it will give you a fresh authentication code so you don't have to wait until the code refreshes by itself.