Search code examples
google-appsgoogle-api-java-clientgoogle-apps-marketplacegoogle-directory-api

Getting "401 Unauthorized" error immediately after Google Marketplace app install, but then works


I recently started to have a problem when users installed my Google App from Google Apps Marketplace.

As soon as the app is installed and the user clicks on the "Launch app" button to get redirected to my site, I do a check to see if the user is an admin. This requires connecting to the Google Directory API using OAuth2.

If I click the "Launch app" button as soon as it appears, I will get a "401 Unauthorized" response from Google when trying to verify the user. But if I wait a couple of seconds before I click, everything works fine.

I tried to solve this by adding a delay of 5 seconds and a retry if the first attempt fails. This works in many cases, but I have still been able to reproduce the error.

I could just wait for another 5 seconds and try again, but that is of course not an ideal solution. Is there a better way of doing this?

I am running version 1.20.0 of the google api java client.

This is the stacktrace i get:

com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized
    at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105) ~[google-oauth-client-1.20.0.jar:1.20.0]
    at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287) ~[google-oauth-client-1.20.0.jar:1.20.0]
    at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307) ~[google-oauth-client-1.20.0.jar:1.20.0]
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:384) ~[google-api-client-1.20.0.jar:1.20.0]
    at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489) ~[google-oauth-client-1.20.0.jar:1.20.0]
    at ... my code

As you can see I am running refreshToken() method. I do this to verify that the connection will work.


Solution

  • That lag seems to be fairly common, and it's not due to any fault on your end. The best workaround is likely to have some retry logic in your application so you can handle this situation.