TokenResponseException: 401 Unauthorized

1.5k views Asked by At

I want to implement Google Sheet API request using service account. I created this code:

HttpTransport httpTransport = new NetHttpTransport();
        JacksonFactory JSON_FACTORY = new JacksonFactory();

        ClassLoader classLoader = this.getClass().getClassLoader();
        java.io.File path = new java.io.File(classLoader.getResource("i-6dc0c917ee63.p12").getFile());

        GoogleCredential credential = new GoogleCredential.Builder()
            .setTransport(httpTransport)
            .setJsonFactory(JSON_FACTORY)
            .setServiceAccountId("[email protected]")
            .setServiceAccountPrivateKeyFromP12File(path)
            .setServiceAccountScopes(Arrays.asList(SheetsScopes.SPREADSHEETS))
            .setServiceAccountUser("[email protected]")
            .build();

        Sheets service = new Sheets.Builder(httpTransport, JSON_FACTORY, null)
            .setApplicationName("project")
            .setHttpRequestInitializer(credential).build();

        Sheets.Spreadsheets spreadsheets = service.spreadsheets();
        Spreadsheet includeGridData = spreadsheets.get(spreadsheetId).execute();

But I get this error:

com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized

at this method .execute();

Do you know how I can fix this issue?

2

There are 2 answers

2
Teyam On

Based from Standard Error Responses, an error 401 is due to invalidCredentials and this indicates that the auth token is invalid or has expired.

Recommended Action:

Do not retry without fixing the problem. You need to get a new auth token.

With this, you may want to check Token Expiration which mentioned that you must write your code to anticipate the possibility that a granted token might no longer work. It also gives these possible reasons why a token might stop working:

  • The user has revoked access.
  • The token has not been used for six months.
  • The user changed passwords and the token contains Gmail scopes.
  • The user account has exceeded a certain number of token requests.

Hope that helps!

0
Arier On

I was having the same issue and it was driving me insane. I had 2 different copies of the same app, using the same credentials.json, but I'd get a successful response in one, but a 401 unauthorized in the other. I finally solved it by deleting the StoredCredential. So next time I ran my app I was taken to Google's authentication page, and it worked.

TLDR: delete StoredCredential One way to find it is running find . -name 'StoredCredential' from the root of your application.