Google Translate API 身份验证密钥和用法 [英] Google Translate API authentication key and usage

查看:449
本文介绍了Google Translate API 身份验证密钥和用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

From https://cloud.google.com/translate/docs/basic/setup-basic, there's a need to set the environmental variable:

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

然后可以发出 curl 请求:

Then a curl request can be made as such:

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 身份验证密钥.

Where there is a Bearer authentication key in the header of the request that comes from the value of the gcloud auth application-default print-access-token command.

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

After trying several calls to gcloud auth application-default print-access-token, every call seems to create a unique token per call.

我的问题是,

  • print-access-token 中的身份验证密钥在到期之前持续多长时间?

  • How long does the authentication key from print-access-token lasts before it expires?

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

Is there a way to create a fix key that isn't dynamically generated from gcloud auth application-default print-access-token and without the need to setup the environmental variable?

有没有办法在不调用 gcloud 命令行可执行文件的情况下以编程方式生成 print-access-token?

Is there a way to generate the print-access-token programmatically without calling the gcloud command line executable?

似乎还有一种方法可以创建静态密钥并按照 https://cloud.google.com/docs/authentication/api-keys 和例如https://github.com/eddiesigner/Sketch-translate-me/wiki/Generate-a-Google-API-Key

There are also seems to be a way to create a static key and use it as described in https://cloud.google.com/docs/authentication/api-keys and e.g. https://github.com/eddiesigner/sketch-translate-me/wiki/Generate-a-Google-API-Key

如何在 curl 调用中使用静态密钥代替 Authorization: Bearer?

推荐答案

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

How long does the authentication key from print-access-token lasts before it expires?

print-access-token 为您提供一个持续时间为 1 小时的 Google 访问令牌.您可以使用 令牌检查过期时间信息端点:

print-access-token gives you a Google access token which has a duration of 1 hour. You can check the expiration time using the token info endpoint :

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

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

Note that the token info works both for checking access_token and for id_token

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

Is there a way to create a fix key that isn't dynamically generated from gcloud auth application-default print-access-token and without the need to setup the environmental variable?

您在向翻译 API 提出请求时下载的凭证文件是为服务帐户制作的 又名服务器到服务器交互

The credential file you have downloaded when making request to the translation API is made for service accounts aka server-to-server interactions

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

It's possible to re-create the flow that is used by the gcloud CLI using a small script that would :

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

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

The complete guide for this flow is located here: https://developers.google.com/identity/protocols/oauth2/service-account#authorizingrequests

这是 中的一个示例.你需要安装 pycryptopyjwt 来运行这个脚本:

Here is an example in python. You will need to install pycrypto and pyjwt to run this script :

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

Note that in the addendum, it's mentionned that some Google API doesn't need Access token and can work just by using the JWT in the Authorization header but it doesn't work for this translation API

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

Also, I guess you would want to use google client library to do the steps above depending on what language you use

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

How can the static key be used in the the curl call in place of the Authorization: Bearer?

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

You need to generate an API key in Google console (and have translation API enabled). Then you can use directly :

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

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

Note that using www.googleapis.com also works :

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 作为查询参数传递:

Note that you could also use POST instead of GET like in the documentation but passing key as a query parameter :

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())

这篇关于Google Translate API 身份验证密钥和用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆