简体   繁体   中英

Accessing Google Sheets API through a service account impersonating a user through domain-wide delegation fails

Example code

from google.oauth2 import service_account 
import pygsheets

creds = service_account.Credentials.from_service_account_file(
    'my/path/to/credentials.json',
    scopes=('https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'),
    subject='account@mydomain.com'
)
pg = pygsheets.authorize(custom_credentials=creds)
pg.open_by_url('https://docs.google.com/spreadsheets/d/my_spreadsheet_id/edit#gid=my_sheet_id')

Problematic behaviour

Fails on the last line with Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.

Expected behaviour

The last line provides an object for Google Sheets access.

Additional info

  • Domain-wide delegation is enabled for the service account, subject account is on the domain
  • Sheet is shared with the subject account
  • When I don't provide the subject and share the sheet with the service account directly, it works

Environment

  • python==3.6.9
  • pygsheets==2.0.3.1
  • google-auth==1.6.3

To consider when using domain-wide delegation

The domain-wide delegation is not enabled by default. To allow it you need to follow the steps described in the documentation .

  1. Step: in the GCP console:
  • You need to activate the checkbox Enable G Suite Domain-wide Delegation for each service account you want to use for such purpose To you use the service account to impersonate a user, you need to give the necessary permissions in the Admin console
  1. In the Admin console:
  • Any scopes that the service account needs when impersonating a user have to be authorized in the admin console
  • For this go to Main menu menu> Security > API controls.
  • Add (if not already done) the service account of interest by its Client ID , provide it all the scopes it needs and authorize
  • You can modify the scopes anytime at a later stage if needed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM