question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

google.auth.exceptions.RefreshError using delegated credentials

See original GitHub issue

Hi,

I’m trying to use the Google API client to retrieve email for a user using a service account. I’ve created the service account credentials with a role of Project Owner, and with domain-wide delegation enabled. However, when I try to connect as a particular user I get:

Traceback (most recent call last):
  File "gmail.py", line 43, in <module>
    messages = ListMessages(service, 'example@example.com')
  File "gmail.py", line 22, in ListMessages
    response = service.users().messages().list(userId=user).execute()
  File "/home/ubuntu/.local/lib/python2.7/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/home/ubuntu/.local/lib/python2.7/site-packages/googleapiclient/http.py", line 846, in execute
    method=str(self.method), body=self.body, headers=self.headers)
  File "/home/ubuntu/.local/lib/python2.7/site-packages/googleapiclient/http.py", line 164, in _retry_request
    resp, content = http.request(uri, method, *args, **kwargs)
  File "/home/ubuntu/.local/lib/python2.7/site-packages/google_auth_httplib2.py", line 187, in request
    self._request, method, uri, request_headers)
  File "/home/ubuntu/.local/lib/python2.7/site-packages/google/auth/credentials.py", line 122, in before_request
    self.refresh(request)
  File "/home/ubuntu/.local/lib/python2.7/site-packages/google/oauth2/service_account.py", line 322, in refresh
    request, self._token_uri, assertion)
  File "/home/ubuntu/.local/lib/python2.7/site-packages/google/oauth2/_client.py", line 145, in jwt_grant
    response_data = _token_endpoint_request(request, token_uri, body)
  File "/home/ubuntu/.local/lib/python2.7/site-packages/google/oauth2/_client.py", line 111, in _token_endpoint_request
    _handle_error_response(response_body)
  File "/home/ubuntu/.local/lib/python2.7/site-packages/google/oauth2/_client.py", line 61, in _handle_error_response
    error_details, response_body)
google.auth.exceptions.RefreshError: ('unauthorized_client: Client is unauthorized to retrieve access tokens using this method.', u'{\n  "error": "unauthorized_client",\n  "error_description": "Client is unauthorized to retrieve access tokens using this method."\n}')

In terms of software versions I have:

google-api-python-client (1.7.7) google-auth (1.6.2) google-auth-httplib2 (0.0.3)

Here’s the code I’m using:

from google.oauth2 import service_account
import googleapiclient.discovery

SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
SERVICE_ACCOUNT_FILE = 'service-account.json'


def ListMessages(service, user):

        response = service.users().messages().list(userId=user).execute()
        messages = response['messages']

        while 'nextPageToken' in response:
                page_token = response['nextPageToken']
                response = service.users().messages().list(userId=user, pageToken=page_token).execute()
                messages.extend(response['messages'])

        return messages


if __name__ == "__main__":
        credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
        delegated_credentials = credentials.with_subject('example@example.com')
        service = googleapiclient.discovery.build('gmail', 'v1', credentials=delegated_credentials)


        messages = ListMessages(service, 'example@example.com')

Any help appreciated.

Thanks, Tom

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:10 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
mthaddoncommented, Jan 12, 2019

I’ve discovered that credentials.token is empty and credentials.valid is False. Looks like there are additional steps needed to authorize the credentials? I’m following https://developers.google.com/api-client-library/python/auth/service-accounts and https://developers.google.com/gmail/api/quickstart/python for the GMail API portion but don’t see any steps to authorize beyond what I’m doing above.

1reaction
mthaddoncommented, Jan 16, 2019

I was able to get this working, thanks. The fix was to delete any non-service-account credentials for this account (I’d set up some oauth credentials as well). Is there somewhere I could propose a doc update to clarify this?

Read more comments on GitHub >

github_iconTop Results From Across the Web

'access_denied: Account restricted' using a domain wide ...
google.auth.exceptions.RefreshError: ('access_denied: Account restricted' using a domain wide delegated account · Ask Question. Asked ...
Read more >
Source code for google.auth.impersonated_credentials
Raises: google.auth.exceptions. ... HTTP connection error google.auth.exceptions.RefreshError: Raised if the impersonated credentials are not available.
Read more >
Using OAuth 2.0 for Server to Server Applications | Authorization
A service account's credentials include a generated email address that is unique and at least one public/private key pair. If domain-wide delegation is...
Read more >
Domain Wide-delegation Issue: Unauthorized Client
RefreshError (error_details, response_data) google.auth.exceptions. ... to activate Google Ads API in GCP and the credentials in my Python ...
Read more >
google-auth Documentation - Read the Docs
Raises google.auth.exceptions.RefreshError – If the Compute Engine metadata service can't be reached if if the instance has not credentials.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found