Ошибка функции Google Cloud 401 при использовании ключа учетной записи службыPython

Программы на Python
Anonymous
Ошибка функции Google Cloud 401 при использовании ключа учетной записи службы

Сообщение Anonymous »

Я пытаюсь пройти аутентификацию в Python для GCP, чтобы вызвать облачные функции.
Я настроил учетную запись службы со следующими ролями
Изображение

и создайте для него ключ JSON. Двойная проверка на панели «Облачные функции» показывает, что его разрешения верны (также попробовал предоставить права администратора)
Изображение

Однако аутентификация, похоже, всегда проходит успешно, несмотря ни на что
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

но позже токен-носитель, похоже, не предоставляет мне доступ к API, поскольку я получаю ошибку 401

Bearer error="invalid_token" error_description="Токен доступа не может быть проверен"

Я пытался повторно создать ключ 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())


Подробнее здесь: https://stackoverflow.com/questions/786 ... ccount-key

Вернуться в «Python»