Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Configurer l'API Devices
Cette page explique comment configurer l'API Devices de Cloud Identity. Vous pouvez utiliser l'API Devices pour provisionner des ressources de manière programmatique (par exemple, pour gérer des groupes Google) au nom d'un administrateur.
Activer l'API et configurer des identifiants
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.
Configurer l'accès à l'API à l'aide d'un compte de service avec délégation au niveau du domaine
Cette section explique comment créer et utiliser un compte de service pour accéder aux ressources Google Workspace. L'authentification directe auprès de l'API Devices à l'aide d'un compte de service n'est pas prise en charge. Vous devez donc utiliser cette méthode.
Créer un compte de service et le configurer pour la délégation au niveau du domaine
Pour créer un compte de service et télécharger la clé de compte de service, procédez comme suit :
Pour créer un compte de service, procédez comme suit :
Dans la console Google Cloud , accédez à la page "Comptes de service IAM" :
Sous Détails du compte de service, saisissez un nom, un ID et une description pour le compte de service, puis cliquez sur Créer et continuer.
Facultatif : Sous Autoriser ce compte de service à accéder au projet, sélectionnez les rôles IAM à attribuer au compte de service.
Cliquez sur Continuer.
Facultatif : Sous Autoriser les utilisateurs à accéder à ce compte de service, ajoutez les utilisateurs ou les groupes autorisés à utiliser et à gérer le compte de service.
Pour créer et télécharger une clé de compte de service, procédez comme suit.
Cliquez sur l'adresse e-mail du compte de service que vous avez créé.
Cliquez sur l'onglet Clés.
Dans la liste déroulante Ajouter une clé, sélectionnez Créer une clé.
Cliquez sur Créer.
Un fichier d'identifiants au format JSON contenant une nouvelle paire de clés publique et privée est généré et téléchargé sur votre ordinateur. Le fichier contient la seule copie des clés. Il vous incombe de la stocker en toute sécurité. Si vous perdez la paire de clés, vous devez en générer une autre.
Examiner les entrées de journal
Lorsque vous examinez les entrées de journal, notez que les journaux d'audit indiquent que toutes les actions du compte de service ont été initiées par l'utilisateur. En effet, la délégation au niveau du domaine fonctionne en permettant au compte de service d'emprunter l'identité d'un administrateur.
Initialiser les identifiants
Lorsque vous initialisez l'identifiant dans votre code, spécifiez l'adresse e-mail avec laquelle le compte de service agit en appelant with_subject() sur l'identifiant.
Exemple :
SERVICE_ACCOUNT_CREDENTIAL_FILE : fichier de clé de compte de service que vous avez créé précédemment dans ce document
USER : l'utilisateur dont le compte de service emprunte l'identité
Vous pouvez maintenant commencer à appeler l'API Devices.
Pour vous authentifier en tant qu'utilisateur final, remplacez l'objet credential du compte de service par l'objet credential que vous pouvez obtenir dans Obtenir des jetons OAuth 2.0.
Installer la bibliothèque cliente Python
Pour installer la bibliothèque cliente Python, exécutez la commande suivante :
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 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)."]]