【问题标题】:Google Translate API authentication key and usageGoogle Translate API 身份验证密钥和用法
【发布时间】:2020-09-20 16:39:38
【问题描述】:

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

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

然后可以这样发出 curl 请求:

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"
  

在来自gcloud auth application-default print-access-token 命令值的请求标头中有Bearer 身份验证密钥。

在尝试多次调用gcloud auth application-default print-access-token 后,每次调用似乎都会为每个调用创建一个唯一令牌。

我的问题是,

  • 来自print-access-token 的身份验证密钥在过期之前持续多久?

  • 有没有办法创建一个不是从gcloud auth application-default print-access-token 动态生成的修复密钥,并且无需设置环境变量?

  • 有没有办法在不调用gcloud 命令行可执行文件的情况下以编程方式生成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 调用中使用静态键来代替 Authorization: Bearer

【问题讨论】:

  • 我认为本教程可能对这两个概念都不清楚:gcloud 生成的令牌和服务帐户密钥。您是否尝试过简单地传递凭据而不是生成的令牌?更改标题:Bearer: "$(cat /path/to/credentials.json)(或者打印环境变量而不是文件)。

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


【解决方案1】:

有没有办法创建一个不是从 gcloud auth application-default print-access-token 动态生成的修复密钥,并且不需要设置环境变量?

使用 api-key 可以更简单地使用谷歌翻译 api。

一步一步...

https://console.cloud.google.com/apis/credentials?project=your-project-id

使用生成的api-key的代码示例如下。

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://translation.googleapis.com/language/translate/v2?API-KEY');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$text1="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.";
$text2="this is second text example";
$post = array(
    'q'=> json_encode(array($text1,$text2)),
    'source'=>"en",
    'target'=> "sr",//serbian sr
    'format'=>"text",   
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$result=json_decode($response,true);
print_r($result['data']['translations']);

【讨论】:

    【解决方案2】:

    来自 print-access-token 的身份验证密钥在过期之前持续多长时间?

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

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

    请注意,令牌信息适用于检查 access_tokenid_token

    有没有办法创建非动态生成的修复密钥 来自 gcloud auth application-default print-access-token 并且没有 需要设置环境变量吗?

    您在向翻译 API 发出请求时下载的凭据文件是为 service accounts aka 服务器到服务器交互而制作的

    可以使用以下小脚本重新创建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 不需要访问令牌,只需使用 Authorization 标头中的 JWT 即可工作,但不适用于此翻译 API

    另外,我猜您可能想使用谷歌客户端库来执行上述步骤,具体取决于您使用的语言

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

    您需要在 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())
    

    【讨论】:

      猜你喜欢
      • 2021-01-22
      • 1970-01-01
      • 2016-01-29
      • 2019-02-17
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多