在从 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:
curl "https://sheets.googleapis.com/v4/spreadsheets/$SPREADSHEET_ID" \
-H "Authorization: Bearer $ACCESS_TOKEN"
注意:您可以找到使用服务帐户密钥调用谷歌翻译APIhere的示例