代码之家  ›  专栏  ›  技术社区  ›  Jan Krynauw

使用Google计算引擎上的应用程序默认凭据访问Sheets API

  •  0
  • Jan Krynauw  · 技术社区  · 6 年前

    ADC(应用程序默认凭据)工作流是否只支持Google Cloud API(例如,支持Google Cloud Storage API,而不支持Google Sheet API)?

    我指的是 google.auth's default method

    如果设置 GOOGLE_APPLICATION_CREDENTIALS 私有密钥文件的环境变量,比如key.json。这与 default 方法按照 google.auth 包裹: 1. If the environment variable GOOGLE_APPLICATION_CREDENTIALS is set to the path of a valid service account JSON private key file, then it is loaded and returned.

    import google.auth
    from apiclient import discovery
    
    credentials, project_id = google.auth.default(scopes=['https://www.googleapis.com/auth/spreadsheets'])
    
    sheets = discovery.build('sheets', 'v4', credentials=credentials)
    
    SPREADSHEETID = '....'
    
    result = sheets.spreadsheets().values().get(spreadsheetId=SPREADSHEETID, range='Sheet1!A:B').execute()
    
    print result.get('values', [])
    

    现在,看看方法的第4步: 4. If the application is running in Compute Engine or the App Engine flexible environment then the credentials and project ID are obtained from the Metadata Service.

    谷歌应用程序证书 环境变量在Google计算实例上,我得到以下错误:

    googleapiclient.errors.HttpError: <HttpError 403 when requesting https://sheets.googleapis.com/v4/spreadsheets/..../values/Sheet1%21A%3AB?alt=json returned "Request had insufficient authentication scopes.">

    find out what credentials you need

    you don't need any credentials

    1 回复  |  直到 6 年前
        1
  •  2
  •   F10    6 年前

    根据 this documentation Oauth 2.0 授权。因此,需要用户登录和同意。