使用服务账号密钥调用GCP Cloud Functions时遇401无效令牌错误
GCP Cloud Functions调用401认证问题
我正尝试通过Python完成GCP认证以调用Cloud Functions,已创建具备对应角色的服务账号并生成JSON密钥,且在Cloud Functions面板确认权限配置正确(也曾尝试赋予Admin权限)。
认证环节始终能成功执行:
from google.oauth2 import service_account import google.auth.transport.requests key_path = "path/to/key.json" scopes = ['https://www.googleapis.com/auth/cloud-platform'] credentials = service_account.Credentials.from_service_account_file( key_path, scopes=scopes ) auth_request = google.auth.transport.requests.Request() credentials.refresh(auth_request) print(credentials.token) # Bearer xxxxx
但后续使用Bearer令牌调用API时,始终返回401错误:
Bearer error="invalid_token" error_description="The access token could not be verified"
我已多次重新生成JSON密钥,且该函数的公开版本测试正常。
补充尝试
我还按照文档创建JWT,代码如下,但仍无法完成授权,认证环节依旧无问题:
import json import datetime import jwt import requests # Load the service account key file key_file_path = "path/to/key.json" with open(key_file_path) as f: service_account_info = json.load(f) # Extract the necessary information from the service account info private_key = service_account_info['private_key'] client_email = service_account_info['client_email'] # Define the JWT headers and payload headers = { "alg": "RS256", "typ": "JWT", "kid": service_account_info['private_key_id'] } now = datetime.datetime.utcnow() expiry = now + datetime.timedelta(hours=1) payload = { "iss": client_email, "sub": client_email, "aud": "https://www.googleapis.com/oauth2/v4/token", "iat": now, "exp": expiry, "scope": "https://www.googleapis.com/auth/cloud-platform" } # Generate the JWT jwt_token = jwt.encode(payload, private_key, algorithm="RS256", headers=headers) # Define the request to get the Google-signed ID token token_url = "https://www.googleapis.com/oauth2/v4/token" headers = { "Content-Type": "application/x-www-form-urlencoded" } body = { "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "assertion": jwt_token } # Make the request to get the ID token response = requests.post(token_url, headers=headers, data=body) # Print the response (contains the ID token) if response.status_code == 200: id_token = "bearer "+response.json().get('access_token') print("ID Token:", id_token) else: print("Error:", response.json())
内容的提问来源于stack exchange,提问作者davide m.
相关产品推荐
相关产品推荐

