如何使用 Python SDK 和内联凭据向 Google Gemini Pro Vision AI 进行身份验证?

问题描述 投票:0回答:1

我正在尝试使用 Google 的 Vertex Python SDK,但我不想随身携带

credentials.json
文件。我宁愿将文件的秘密部分存储在 Key Vault 中并在运行时插入。但我找不到一种简单的方法来使用内联字典来定义凭据。

from_service_account_file
需要一个文件路径。

示例脚本

import io
import json
import logging

from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
from google.auth.transport.requests import Request
from google.oauth2.service_account import Credentials

# ----------------------------------------------------------------

AZURE_KEYVAULT_URL = 'https://my-kv-name.vault.azure.net/'

GCP_PROJECT_ID = 'my-proj'
GCP_REGION = 'my-region'

logging.basicConfig(level=logging.INFO)

# ----------------------------------------------------------------

def get_secrets_from_key_vault(key_vault_url, secret_names):   
    az_credential = DefaultAzureCredential()  
    secret_client = SecretClient(vault_url=key_vault_url, credential=az_credential)   
    secrets = {}  
    for secret_name in secret_names:  
        secret = secret_client.get_secret(secret_name)  
        secrets[secret_name] = secret.value  
  
    return secrets 

# -----------------------------------------------------------------

secret_names = [
    'secret1', 
    'secret2'
  ]

secret_values = get_secrets_from_key_vault(AZURE_KEYVAULT_URL, secret_names)

gcp_credentials = {
  "type": "service_account",
  "project_id": "vertexai-poc-400414",
  "private_key_id": secret_values['secret1'],
  "private_key": secret_values['secret2'],
  "client_email": "[email protected]",
  "client_id": "long-number-here",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/[email protected]",
  "universe_domain": "googleapis.com"
}

# The `from_service_account_file` wants a file path, not a dict. I can't find an alternative method.

gcp_credentials = Credentials.from_service_account_file(  # <---problem is here. 
    gcp_credentials_string,
    scopes = ['https://www.googleapis.com/auth/cloud-platform'])

# Handle auth refresh
if gcp_credentials.expired:
    gcp_credentials.refresh(Request())

google-cloud-platform google-api-python-client google-cloud-vertex-ai
1个回答
0
投票

我建议您使用base64对服务帐户JSON密钥文件内容进行编码。将其作为字符串存储在保管库中。当你读到秘密时,做相反的事情。

Credentials.from_service_account_file
替换为
Credentials.from_service_account_info
并使用
json.loads()
将base64解码的字符串转换为
from_service_account_info
可以使用的字典。

请参阅文档了解更多信息:

google.oauth2.service_account 模块

© www.soinside.com 2019 - 2024. All rights reserved.