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

查看:854
本文介绍了Google翻译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'

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

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"
  

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

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?

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

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

似乎也有一种创建静态密钥并使用它的方法,如 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?

How can the static key be used in the the curl call in place of the 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应用程序的默认打印访问令牌,无 需要设置环境变量吗?

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发出请求
  • build and encode the JWT payload from the data from credentials files (to populate aud, iss, sub, iat and exp)
  • request an access token using that JWT
  • make the request to the API using this access token

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

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不需要Access令牌,仅通过使用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

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

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也可以:

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翻译API身份验证密钥和用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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