Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
El dispositivo aislado de Vertex AI en Google Distributed Cloud (GDC) proporciona APIs y servicios que requieren autenticación. La autenticación es la forma en que demuestras tu identidad para acceder a los servicios con tokens.
Los tokens son objetos digitales que verifican que un emisor proporcionó las credenciales adecuadas y que se intercambiaron correctamente por el token. El token contiene información sobre la identidad de la cuenta solicitante y el acceso específico que está autorizado a tener.
En esta página, se describe cómo autenticarse en las APIs de Vertex AI de manera programática. En esta página, se describen los pasos para obtener un token de autenticación para tus solicitudes a la API, según si accedes a las APIs de Vertex AI como usuario o con una cuenta de servicio.
Elige una de las siguientes opciones para obtener un token de autenticación:
Cuenta de usuario
Sigue estos pasos para obtener un token de autenticación con permisos de usuario:
Para acceder al servicio de Vertex AI que deseas usar, otorga a tu cuenta de usuario el rol correspondiente que se indica en Prepara los permisos de IAM.
Accede al dispositivo aislado de GDC con la cuenta de usuario con la que debes interactuar con la API:
Según el uso previsto del token de autenticación, es posible que debas incluir el puerto después del extremo de servicio en la ruta de acceso de los públicos de la siguiente manera:
Si usas una biblioteca cliente para tu solicitud, debes incluir el puerto :443 después del extremo del servicio en la ruta de acceso a los públicos. Por lo tanto, la ruta de acceso --audiences en el comando debe ser https://ENDPOINT:443.
Si usas gRPC, curl o llamadas de REST programáticas para tu solicitud, no incluyas el puerto. Por lo tanto, la ruta de acceso --audiences en el comando debe ser https://ENDPOINT.
El resultado muestra el token de autenticación. Agrega el token al encabezado de las solicitudes de línea de comandos que realices, como en el siguiente ejemplo:
-H"Authorization: Bearer TOKEN"
Reemplaza TOKEN por el valor del token de autenticación que muestra el resultado.
Cuenta de servicio
Sigue estos pasos para obtener un token de autenticación con una cuenta de servicio:
Otorga a la cuenta de servicio el rol correspondiente que se indica en Prepara los permisos de IAM para permitirle acceder al servicio que deseas usar.
Agrega el siguiente código a una secuencia de comandos de Python:
importosimportgoogle.authfromgoogle.auth.transportimportrequestsimportrequestsasreqsos.environ["GOOGLE_APPLICATION_CREDENTIALS"]="PATH_TO_SERVICE_KEY"os.environ["GRPC_DEFAULT_SSL_ROOTS_FILE_PATH"]="CERT_NAME"# If you use a client library for your request,# you must include port :443 after the service endpoint# in the audience path.audience="https://ENDPOINT"creds,project_id=google.auth.default()print(project_id)creds=creds.with_gdch_audience(audience)deftest_get_token():sesh=reqs.Session()req=requests.Request(session=sesh)creds.refresh(req)print(creds.token)if__name__=="__main__":test_get_token()
Reemplaza lo siguiente:
PATH_TO_SERVICE_KEY: Es la ruta de acceso al archivo JSON que contiene los pares de claves de tu cuenta de servicio.
CERT_NAME: Es el nombre del archivo del certificado de la autoridad certificadora (CA), como org-1-trust-bundle-ca.cert. Solo necesitas este valor si estás en un entorno de desarrollo. De lo contrario, omítelo.
ENDPOINT: Es el extremo del servicio que usas para tu organización. Para obtener más información, consulta el estado y los extremos del servicio. Según el uso previsto del token de autenticación, es posible que debas incluir el puerto después del extremo de servicio en la ruta de acceso del público de la siguiente manera:
Si usas una biblioteca cliente para tu solicitud, debes incluir el puerto :443 después del extremo del servicio en la ruta de acceso del público. Por lo tanto, la ruta de acceso audience en la secuencia de comandos debe ser "https://ENDPOINT:443".
Si usas gRPC, curl o llamadas de REST programáticas para tu solicitud, no incluyas el puerto. Por lo tanto, la ruta de acceso audience en la secuencia de comandos debe ser "https://ENDPOINT".
Guarda la secuencia de comandos de Python.
Ejecuta la secuencia de comandos de Python para recuperar el token:
pythonSCRIPT_NAME
Reemplaza SCRIPT_NAME por el nombre que le diste a tu secuencia de comandos de Python, como token.py.
El resultado muestra el token de autenticación. Agrega el token al encabezado de las solicitudes de línea de comandos que realices, como en el siguiente ejemplo:
-H"Authorization: Bearer TOKEN"
Reemplaza TOKEN por el valor del token de autenticación que muestra el resultado.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-04 (UTC)"],[],[],null,["# Authenticate API requests\n\nVertex AI on Google Distributed Cloud (GDC) air-gapped appliance provides APIs\nand services that require authentication. Authentication is how you prove your\nidentity to access services by using tokens.\n\nTokens are digital objects that verify a caller provided proper credentials and\nthat they have been successfully exchanged for the token. The token carries\ninformation about the identity of the requesting account and the specific access\nit is authorized to have.\n\nThis page describes how to authenticate to Vertex AI APIs\nprogrammatically. Depending on whether you access the Vertex AI\nAPIs as a user or with a service account, this page describes the steps to get\nan authentication token for your API requests.\n\nChoose one of the following options to get an authentication token: \n\n### User account\n\nFollow these steps to get an authentication token with user permissions:\n\n1. Note [the endpoint of the API](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vertex-ai-api-status) you want to use.\n\n2. Gain access to the Vertex AI service you want to use by granting your user account the corresponding role listed in [Prepare IAM permissions](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vertex-ai-ao-permissions).\n\n3. Sign in to GDC air-gapped appliance with the user account you have to interact with the API:\n\n gdcloud auth login\n\n4. Get the authentication token:\n\n gdcloud auth print-identity-token --audiences=https://\u003cvar translate=\"no\"\u003eENDPOINT\u003c/var\u003e\n\n Replace \u003cvar translate=\"no\"\u003eENDPOINT\u003c/var\u003e with the service endpoint that you use for your organization. For more information, [view service status and endpoints](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vertex-ai-api-status).\n\n Depending on the intended use of the authentication token, you might need to include the port after the service endpoint in the audiences path as follows:\n - If you use a [client library](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vertex-ai-install-libraries) for your request, you must include port `:443` after the service endpoint in the audiences path. Therefore, the `--audiences` path in the command must be `https://`\u003cvar translate=\"no\"\u003eENDPOINT\u003c/var\u003e`:443`.\n - If you use gRPC, `curl`, or programmatic REST calls for your request, don't include the port. Therefore, the `--audiences` path in the command must be `https://`\u003cvar translate=\"no\"\u003eENDPOINT\u003c/var\u003e.\n\nThe output displays the authentication token. Add the token to the header of the command-line requests you make, as in the following example: \n\n -H \"Authorization: Bearer \u003cvar translate=\"no\"\u003eTOKEN\u003c/var\u003e\"\n\nReplace \u003cvar translate=\"no\"\u003eTOKEN\u003c/var\u003e with the value for the authentication token that the output displays.\n\n### Service account\n\nFollow these steps to get an authentication token with a service account:\n\n1. Note [the endpoint of the API](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vertex-ai-api-status) you want to use.\n\n2. [Set up the service account](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vertex-ai-set-up-project#set-up-service) you want to use to access the Vertex AI service.\n\n3. Grant the service account the corresponding role listed in [Prepare IAM permissions](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vertex-ai-ao-permissions) to let it gain access to the service you want to use.\n\n4. [Get the service key pairs of your service account](/distributed-cloud/hosted/docs/latest/appliance/platform/pa-user/iam/service-identity#create_and_add_key_pairs).\n\n5. Install the `google-auth` client library:\n\n pip install google-auth\n\n6. Add the following code to a Python script:\n\n import os\n import google.auth\n from google.auth.transport import requests\n import requests as reqs\n\n os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"\u003cvar translate=\"no\"\u003ePATH_TO_SERVICE_KEY\u003c/var\u003e\"\n os.environ[\"GRPC_DEFAULT_SSL_ROOTS_FILE_PATH\"] = \"\u003cvar translate=\"no\"\u003eCERT_NAME\u003c/var\u003e\"\n\n # If you use a client library for your request,\n # you must include port :443 after the service endpoint\n # in the audience path.\n audience = \"https://\u003cvar translate=\"no\"\u003eENDPOINT\u003c/var\u003e\"\n\n creds, project_id = google.auth.default()\n print(project_id)\n creds = creds.with_gdch_audience(audience)\n\n def test_get_token():\n sesh = reqs.Session()\n req = requests.Request(session=sesh)\n creds.refresh(req)\n print(creds.token)\n\n if __name__==\"__main__\":\n test_get_token()\n\n Replace the following:\n - \u003cvar translate=\"no\"\u003ePATH_TO_SERVICE_KEY\u003c/var\u003e: the path to the JSON file that contains the key pairs of your service account.\n - \u003cvar translate=\"no\"\u003eCERT_NAME\u003c/var\u003e: the name of the Certificate Authority (CA) certificate file, such as `org-1-trust-bundle-ca.cert`. You only need this value if you are in a development environment. Otherwise, omit it.\n - \u003cvar translate=\"no\"\u003eENDPOINT\u003c/var\u003e: the service endpoint that you use for your organization. For more information, [view service status and endpoints](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vertex-ai-api-status). Depending on the intended use of the authentication token, you might need to include the port after the service endpoint in the audience path as follows:\n\n - If you use a [client library](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vertex-ai-install-libraries) for your request, you must include port `:443` after the service endpoint in the audience path. Therefore, the `audience` path in the script must be `\"https://`\u003cvar translate=\"no\"\u003eENDPOINT\u003c/var\u003e`:443\"`.\n - If you use gRPC, `curl`, or programmatic REST calls for your request, don't include the port. Therefore, the `audience` path in the script must be `\"https://`\u003cvar translate=\"no\"\u003eENDPOINT\u003c/var\u003e`\"`.\n7. Save the Python script.\n\n8. Run the Python script to fetch the token:\n\n python \u003cvar translate=\"no\"\u003eSCRIPT_NAME\u003c/var\u003e\n\n Replace \u003cvar translate=\"no\"\u003eSCRIPT_NAME\u003c/var\u003e with the name you gave to your Python script, such as `token.py`.\n\nThe output displays the authentication token. Add the token to the header of the command-line requests you make, as in the following example: \n\n -H \"Authorization: Bearer \u003cvar translate=\"no\"\u003eTOKEN\u003c/var\u003e\"\n\nReplace \u003cvar translate=\"no\"\u003eTOKEN\u003c/var\u003e with the value for the authentication token that the output displays."]]