【问题标题】:How can I a Google Api restful endpoint using service key?如何使用服务密钥创建 Google Api RESTful 端点?
【发布时间】:2020-10-06 13:01:17
【问题描述】:

我正在使用邮递员来记忆一个宁静的 api 调用并尝试访问 google sheet API 端点。当我尝试访问我的端点时,它会返回:

{
  "error": {
    "code": 403,
    "message": "The request is missing a valid API key.",
    "status": "PERMISSION_DENIED"
  }
}

这很公平,因为我没有使用我的 API 密钥。我创建了一个服务帐户并获得了一个 json 文件,但我计划使用休息端点访问,因此需要在标头中传递令牌,但我不确定如何。

我查看了 json 文件,但不确定要提取什么以便将其传递给我的休息电话。

有没有人能够成功地做到这一点?

【问题讨论】:

    标签: rest google-api google-oauth google-api-client restful-authentication


    【解决方案1】:

    在从 Postman 调用 Google 服务之前,您需要重新创建流程以获取访问令牌表单服务帐户凭据:

    • 根据凭证文件中的数据构建和编码 JWT 有效负载(以填充 aud、iss、sub、iat 和 exp)
    • 使用该 JWT 请求访问令牌
    • 使用此访问令牌向 API 发出请求

    您可以在此处找到此流程的完整指南:https://developers.google.com/identity/protocols/oauth2/service-account#authorizingrequests

    这里是python中的一个例子。你需要安装 pycrypto 和 pyjwt 来运行这个脚本:

    import requests
    import json
    import jwt
    import time
    
    #for RS256 you may need this
    #from jwt.contrib.algorithms.pycrypto import RSAAlgorithm
    #jwt.register_algorithm('RS256', RSAAlgorithm(RSAAlgorithm.SHA256))
    
    token_url = "https://oauth2.googleapis.com/token"
    credentials_file_path = "./google.json"
    
    #build and sign JWT
    def build_jwt(config):
        iat = int(time.time())
        exp = iat + 3600
        payload = {
            'iss': config["client_email"],
            'sub': config["client_email"],
            'aud': token_url,
            'iat': iat,
            'exp': exp,
            'scope': 'https://www.googleapis.com/auth/spreadsheets'
        }
        jwt_headers = {
            'kid': config["private_key_id"],
            "alg": 'RS256',
            "typ": 'JWT'
        }
        signed_jwt = jwt.encode(
            payload, 
            config["private_key"], 
            headers = jwt_headers,
            algorithm = 'RS256'
        )
        return signed_jwt
    
    with open(credentials_file_path) as conf_file:
        config = json.load(conf_file)
        # 1) build and sign JWT
        signed_jwt = build_jwt(config)
        # 2) get access token
        r = requests.post(token_url, data= {
            "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
            "assertion": signed_jwt.decode("utf-8")
        })
        token = r.json()
        print(f'token will expire in {token["expires_in"]} seconds')
        at = token["access_token"]
        print(at)
    

    注意范围的值:https://www.googleapis.com/auth/spreadsheets

    或许,您可以使用 Google API 库完成上述所有流程,具体取决于什么 你喜欢的编程语言

    上面的脚本将打印访问令牌:

    ya29.AHES67zeEn-RDg9CA5gGKMLKuG4uVB7W4O4WjNr-NBfY6Dtad4vbIZ
    

    然后你就可以在 Postman 的 Authorization 标头中使用它作为 Bearer {TOKEN}。

    或者使用:

    curl "https://sheets.googleapis.com/v4/spreadsheets/$SPREADSHEET_ID" \
         -H "Authorization: Bearer $ACCESS_TOKEN"
    

    注意:您可以找到使用服务帐户密钥调用谷歌翻译APIhere的示例

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 2016-05-29
      • 2021-01-31
      • 1970-01-01
      • 2021-03-30
      • 2017-03-26
      • 2019-04-04
      • 1970-01-01
      • 2017-08-03
      相关资源
      最近更新 更多