Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Configura la API de Devices
En esta página, se explica cómo configurar la API de Cloud Identity Devices. Puedes usar la API de Devices para aprovisionar recursos de forma programática (por ejemplo, administrar Grupos de Google) en nombre de un administrador.
Habilita la API y configura credenciales
Sign in to your Google Cloud account. If you're new to
Google Cloud,
create an account to evaluate how our products perform in
real-world scenarios. New customers also get $300 in free credits to
run, test, and deploy workloads.
In the Google Cloud console, on the project selector page,
select or create a Google Cloud project.
Configura el acceso a la API con una cuenta de servicio con delegación para todo el dominio
En esta sección, se describe cómo crear y usar una cuenta de servicio para acceder a los recursos de Google Workspace. No se admite la autenticación directa en la API de Devices con una cuenta de servicio, por lo que debes usar este método.
Crea una cuenta de servicio y configúrala para la delegación de todo el dominio
Para crear una cuenta de servicio y descargar su clave, haz lo siguiente:
Para crear una cuenta de servicio, haz lo siguiente:
En la Google Cloud consola, ve a la página de cuentas de servicio de IAM:
Para crear y descargar una clave de cuenta de servicio, haz lo siguiente:
Haz clic en la dirección de correo electrónico de la cuenta de servicio que creaste.
Haz clic en la pestaña Claves.
En la lista desplegable Agregar clave, selecciona Crear clave nueva.
Haz clic en Crear.
Se genera y descarga en tu máquina un archivo de credenciales con formato JSON que contiene un nuevo par de claves públicas y privadas. El archivo contiene la única copia de las claves. Tú eres responsable de almacenarla de forma segura. Si pierdes el par de claves, deberás generar uno nuevo.
Revisa las entradas de registro
Cuando revises las entradas de registro, ten en cuenta que los registros de auditoría mostrarán las acciones de la cuenta de servicio como si las hubiera iniciado el usuario. Esto se debe a que la delegación en todo el dominio funciona permitiendo que la cuenta de servicio suplante la identidad de un usuario administrador.
Inicializa las credenciales
Cuando inicialices la credencial en el código, especifica la dirección de correo electrónico en la que actúa la cuenta de servicio llamando a with_subject() en la credencial.
Por ejemplo:
SERVICE_ACCOUNT_CREDENTIAL_FILE: Es el archivo de claves de la cuenta de servicio que creaste anteriormente en este documento.
USER: el usuario al que suplanta la cuenta de servicio
Ahora puedes comenzar a realizar llamadas a la API de dispositivos.
Si quieres autenticarte como usuario final, reemplaza el objeto credential de la cuenta de servicio por el objeto credential que puedes obtener en Obtén tokens de OAuth 2.0.
Instala la biblioteca cliente para Python
Para instalar la biblioteca cliente de Python, ejecuta el siguiente comando:
[[["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)"],[[["\u003cp\u003eThe Cloud Identity Devices API is set up using a service account with domain-wide delegation, as direct authentication via a service account is not supported.\u003c/p\u003e\n"],["\u003cp\u003eSetting up involves creating a service account, configuring domain-wide delegation to allow the service account to access the Devices API, and creating a downloadable service account key.\u003c/p\u003e\n"],["\u003cp\u003eService account keys pose a security risk if not handled correctly, requiring careful management and secure storage, or alternative authentication methods if possible.\u003c/p\u003e\n"],["\u003cp\u003eAudit logs will display service account actions as being initiated by the user because the service account impersonates an administrator user via domain-wide delegation.\u003c/p\u003e\n"],["\u003cp\u003eCredential initialization in your code requires specifying the email address the service account acts on, and a Python client library can be installed via the \u003ccode\u003epip\u003c/code\u003e command.\u003c/p\u003e\n"]]],[],null,["# Set up the Devices API\n======================\n\nThis page explains how to set up the Cloud Identity Devices API. You can use the\nDevices API to programmatically provision resources---for example\nmanaging Google Groups---on behalf of an administrator.\n\nEnable the API and setting up credentials\n-----------------------------------------\n\n- Sign in to your Google Cloud account. If you're new to Google Cloud, [create an account](https://console.cloud.google.com/freetrial) to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Identity API.\n\n\n [Enable the API](https://console.cloud.google.com/flows/enableapi?apiid=cloudidentity.googleapis.com)\n\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Identity API.\n\n\n [Enable the API](https://console.cloud.google.com/flows/enableapi?apiid=cloudidentity.googleapis.com)\n\nSet up API access using a service account with domain-wide delegation\n---------------------------------------------------------------------\n\nThis section describes how to create and use a [service account](/iam/docs/service-accounts)\nto access Google Workspace resources. Authenticating directly to the\nDevices API using a service account isn't supported, so you\nmust use this method.\n\n### Create a service account and configure it for domain-wide delegation\n\nTo create a service account a download the service account key, do the\nfollowing:\n\n1. To create a service account, do the following:\n\n 1. In the Google Cloud console go to the IAM service accounts\n page:\n\n [Go to service accounts](https://console.cloud.google.com/iam-admin/serviceaccounts)\n 2. Click add **Create service account**.\n\n 3. Under **Service account details** , type a name, ID, and description for the\n service account, then click **Create and continue**.\n\n 4. Optional: Under **Grant this service account access to project**, select\n the IAM roles to grant to the service account.\n\n 5. Click **Continue**.\n\n 6. Optional: Under **Grant users access to this service account**, add the\n users or groups that are allowed to use and manage the service account.\n\n 7. Click **Done**.\n\n2. To let the service account access Devices API by using\n domain-wide delegation, follow the instructions in [Set up domain-wide delegation for the service account](https://support.google.com/a/answer/162106).\n\n3. To create and download a service account key, do the following.\n\n | **Important:** Service account keys are a security risk if not managed correctly. You should [choose a more secure alternative to service account keys](/docs/authentication#auth-decision-tree) whenever possible. If you must authenticate with a service account key, you are responsible for the security of the private key and for other operations described by [Best practices for managing service account keys](/iam/docs/best-practices-for-managing-service-account-keys). If you are prevented from creating a service account key, service account key creation might be disabled for your organization. For more information, see [Managing secure-by-default organization resources](/resource-manager/docs/secure-by-default-organizations).\n |\n |\n | If you acquired the service account key from an external source, you must validate it before use.\n | For more information, see [Security requirements for externally sourced credentials](/docs/authentication/external/externally-sourced-credentials).\n 1. Click the email address for the service account you created.\n 2. Click the **Keys** tab.\n 3. In the **Add key** drop-down list, select **Create new key**.\n 4. Click **Create**.\n\n A JSON-formatted credential file, containing a new public and private key pair,\n is generated and downloaded to your machine. The file contains the only copy of\n the keys. You are responsible for storing it securely. If you lose the key pair,\n you must generate a new one.\n\n### Review log entries\n\nWhen reviewing log entries, note that audit logs will show any service account\nactions as having been initiated by the user. This is because domain-wide\ndelegation works by allowing the service account to impersonate an administrator\nuser.\n\n### Initialize credentials\n\nWhen you initialize the credential in your code, specify the email address on\nwhich the service account acts by calling `with_subject()` on the credential.\nFor example: \n\n### Python\n\n credentials = service_account.Credentials.from_service_account_file(\n '\u003cvar translate=\"no\"\u003eSERVICE_ACCOUNT_CREDENTIAL_FILE\u003c/var\u003e',\n scopes=SCOPES).with_subject(\u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-n\"\u003eUSER\u003c/span\u003e\u003c/var\u003e\n )\n\nReplace the following:\n\n- \u003cvar translate=\"no\"\u003eSERVICE_ACCOUNT_CREDENTIAL_FILE\u003c/var\u003e: the service account key file that you created earlier in this document\n- \u003cvar translate=\"no\"\u003eUSER\u003c/var\u003e: the user that the service account impersonates\n\n#### Instantiating a client\n\nThe following example shows how to instantiate a client using service account\ncredentials. \n\n### Python\n\n from google.oauth2 import service_account\n import googleapiclient.discovery\n\n SCOPES = ['https://www.googleapis.com/auth/cloud-identity.devices']\n\n def create_service():\n credentials = service_account.Credentials.from_service_account_file(\n '\u003cvar translate=\"no\"\u003eSERVICE_ACCOUNT_CREDENTIAL_FILE\u003c/var\u003e',\n scopes=SCOPES\n )\n\n delegated_credentials = credentials.with_subject('\u003cvar translate=\"no\"\u003eUSER\u003c/var\u003e')\n\n service_name = 'cloudidentity'\n api_version = 'v1'\n service = googleapiclient.discovery.build(\n service_name,\n api_version,\n credentials=delegated_credentials)\n\n return service\n\nReplace the following:\n\n- \u003cvar translate=\"no\"\u003eSERVICE_ACCOUNT_CREDENTIAL_FILE\u003c/var\u003e: the service account key file that you created earlier in this document\n- \u003cvar translate=\"no\"\u003eUSER\u003c/var\u003e: the user that the service account impersonates\n\nYou can now begin making calls to the Devices API.\n\nTo instead authenticate as an end-user, replace the `credential` object from the\nservice account with the `credential` you can obtain in [Obtaining OAuth 2.0 tokens](https://developers.google.com/identity/protocols/oauth2/web-server#obtainingaccesstokens).\n\nInstalling the Python client library\n------------------------------------\n\nTo install the Python client library, run the following command: \n\n pip install --upgrade google-api-python-client google-auth \\\n google-auth-oauthlib google-auth-httplib2\n\nFor more on setting up your Python development environment, refer to the\n[Python Development Environment Setup Guide](/python/docs/setup)."]]