Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Configurar a API Devices
Nesta página, explicamos como configurar a API Cloud Identity Devices. É possível usar a
API Devices para provisionar recursos de maneira programática, como
gerenciar grupos do Google, em nome de um administrador.
Ativar a API e configurar as credenciais
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.
Configurar o acesso à API usando uma conta de serviço com delegação em todo o domínio
Esta seção descreve como criar e usar uma conta de serviço
para acessar recursos do Google Workspace. A autenticação direta na API
Devices usando uma conta de serviço não é compatível. Portanto, você
precisa usar esse método.
Criar e configurar uma conta de serviço para delegação em todo o domínio
Para criar uma conta de serviço e fazer o download da chave dela, faça o seguinte:
Para criar uma conta de serviço, faça o seguinte:
No console Google Cloud , acesse a página de contas de serviço do IAM:
Para criar e fazer o download de uma chave de conta de serviço, faça o seguinte:
Clique no endereço de e-mail da conta de serviço que você criou.
Clique na guia Chaves.
Na lista suspensa Adicionar chave, selecione Criar nova chave.
Clique em Criar.
Um arquivo de credenciais formatado em JSON, contendo um novo par de chaves pública e privada,
é gerado e baixado para sua máquina. O arquivo contém a única cópia das chaves. Você é responsável por armazená-la com segurança. Se você perder o par de chaves, será necessário gerar outro.
Analisar entradas de registro
Ao analisar as entradas de registro, observe que os registros de auditoria mostram todas as ações da conta de serviço como se tivessem sido iniciadas pelo usuário. Isso acontece porque a delegação em todo o domínio permite que a conta de serviço represente um usuário administrador.
Inicializar credenciais
Em seguida, ao inicializar a credencial no código, especifique o endereço de e-mail
em que a conta de serviço atua chamando with_subject() na credencial.
Exemplo:
SERVICE_ACCOUNT_CREDENTIAL_FILE: o arquivo de chave da conta de serviço que você criou anteriormente neste documento
USER: o usuário que a conta de serviço personifica
Agora você pode começar a fazer chamadas para a API Devices.
Para autenticar como um usuário final, substitua o objeto credential da
conta de serviço pelo credential que você pode receber em Como receber tokens do OAuth 2.0.
Como instalar a biblioteca de cliente do Python
Para instalar a biblioteca de cliente Python, execute o seguinte comando:
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-18 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)."]]