Google翻译API身份验证密钥和用法

时间:2020-06-02 08:46:00

标签: google-cloud-platform oauth google-api google-translate

https://cloud.google.com/translate/docs/basic/setup-basic中,需要设置环境变量:

export GOOGLE_APPLICATION_CREDENTIALS='/path/to/credential.json'

然后可以这样进行卷曲请求:

curl -s -X POST -H "Content-Type: application/json" \
    -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
    --data "{
  'q': 'The Great Pyramid of Giza (also known as the Pyramid of Khufu or the
        Pyramid of Cheops) is the oldest and largest of the three pyramids in
        the Giza pyramid complex.',
  'source': 'en',
  'target': 'es',
  'format': 'text'
}" "https://translation.googleapis.com/language/translate/v2"
  

在请求的标头中有一个Bearer命令的值的身份验证密钥。

尝试了几次对gcloud auth application-default print-access-token的呼叫后,每个呼叫似乎每次呼叫都会创建一个唯一的令牌。

我的问题是,

  • 来自gcloud auth application-default print-access-token的身份验证密钥在失效之前可以持续多长时间?

  • 是否可以创建不是从print-access-token动态生成且无需设置环境变量的修订密钥?

  • 是否可以通过编程方式生成gcloud auth application-default print-access-token而无需调用print-access-token命令行可执行文件?

似乎也有一种创建静态密钥并按照https://cloud.google.com/docs/authentication/api-keys中所述使用静态密钥的方法,例如https://github.com/eddiesigner/sketch-translate-me/wiki/Generate-a-Google-API-Key

如何在curl调用中使用静态密钥代替gcloud

1 个答案:

答案 0 :(得分:5)

print-access-token的认证密钥在失效之前能持续多长时间?

print-access-token为您提供了一个持续1小时的Google访问令牌。您可以使用token info endpoint来检查到期时间:

https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=YOUR_ACCESS_TOKEN

请注意,令牌信息可同时用于检查access_tokenid_token

有没有办法创建不是动态生成的修复密钥 来自gcloud auth应用程序的默认打印访问令牌,无 需要设置环境变量吗?

service accounts(也称为服务器到服务器的交互)发出向翻译API的请求时下载的凭证文件

可以使用以下小脚本重新创建gcloud CLI使用的流:

  • 根据凭据文件中的数据构建并编码JWT有效负载(以填充audisssubiatexp
  • 使用该JWT请求访问令牌
  • 使用此访问令牌向API发出请求

此流程的完整指南位于:https://developers.google.com/identity/protocols/oauth2/service-account#authorizingrequests

这里是中的一个示例。您将需要安装pycryptopyjwt来运行此脚本:

import requests
import json
import jwt
import time

#for RS256
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/cloud-platform'
    }
    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"]
    # 3) call translate API
    r = requests.post(
        "https://translation.googleapis.com/language/translate/v2",
        headers = {
            "Authorization": f'Bearer {at}'
        },
        json= {
            "q": "The Great Pyramid of Giza (also known as the Pyramid of Khufu or the Pyramid of Cheops) is the oldest and largest of the three pyramids in the Giza pyramid complex.",
            "source": "en",
            "target": "es",
            "format": "text"
        })
    print(r.json())

请注意,在附录中,提到了某些Google API不需要Access令牌,仅通过使用Authorization标头中的JWT即可工作,但不适用于此翻译API

此外,我想您可能希望使用google客户端库来执行上述步骤,具体取决于您使用的语言

如何在curl调用中使用静态键代替 授权:不记名?

您需要在Google控制台中生成API密钥(并启用翻译API)。然后,您可以直接使用:

https://translation.googleapis.com/language/translate/v2?key=YOUR_API_KEY&q=Hello%20world&target=es&alt=json&source=en

请注意,使用www.googleapis.com也可以:

https://www.googleapis.com/language/translate/v2?key=YOUR_API_KEY&q=Hello%20world&target=es&alt=json&source=en

使用

import requests

api_key = "YOUR_API_KEY"
text = "The Great Pyramid of Giza (also known as the Pyramid of Khufu or the Pyramid of Cheops) is the oldest and largest of the three pyramids in the Giza pyramid complex"

r = requests.get(
    "https://translation.googleapis.com/language/translate/v2",
    params = {
        "key": api_key,
        "q": text,
        "target": "es",
        "alt":"json",
        "source":"en"
    }
)
print(r.json())

请注意,您也可以像文档中那样使用POST代替GET,但可以将key作为查询参数:

r = requests.post(
    "https://translation.googleapis.com/language/translate/v2",
    params = {
        "key": api_key
    },
    json = {
        "q": text,
        "target": "es",
        "alt":"json",
        "source":"en"
    }
)
print(r.json())