Configura la API de invitación de usuarios

En esta página, se explica cómo configurar la API de invitación de usuario de Cloud Identity.

Habilita la API y configura las credenciales

  1. Accede a tu cuenta de Google Cloud . Si eres nuevo en Google Cloud, crea una cuenta para evaluar el rendimiento de nuestros productos en situaciones reales. Los clientes nuevos también obtienen $300 en créditos gratuitos para ejecutar, probar y, además, implementar cargas de trabajo.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Enable the Cloud Identity API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  4. Create a service account:

    1. Ensure that you have the Create Service Accounts IAM role (roles/iam.serviceAccountCreator) and the Project IAM Admin role (roles/resourcemanager.projectIamAdmin). Learn how to grant roles.
    2. In the Google Cloud console, go to the Create service account page.

      Go to Create service account
    3. Select your project.
    4. In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.

      In the Service account description field, enter a description. For example, Service account for quickstart.

    5. Click Create and continue.
    6. Grant the Service Account Token Creator role to the service account.

      To grant the role, find the Select a role list, then select Service Account Token Creator.

    7. Click Continue.
    8. Click Done to finish creating the service account.

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Enable the Cloud Identity API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  7. Create a service account:

    1. Ensure that you have the Create Service Accounts IAM role (roles/iam.serviceAccountCreator) and the Project IAM Admin role (roles/resourcemanager.projectIamAdmin). Learn how to grant roles.
    2. In the Google Cloud console, go to the Create service account page.

      Go to Create service account
    3. Select your project.
    4. In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.

      In the Service account description field, enter a description. For example, Service account for quickstart.

    5. Click Create and continue.
    6. Grant the Service Account Token Creator role to the service account.

      To grant the role, find the Select a role list, then select Service Account Token Creator.

    7. Click Continue.
    8. Click Done to finish creating the service account.

Instala la biblioteca cliente de Python

Para instalar la biblioteca cliente de Python, ejecuta el siguiente comando:

  pip install --upgrade google-api-python-client google-auth \
    google-auth-oauthlib google-auth-httplib2

Para obtener más información sobre la configuración de tu entorno de desarrollo de Python, consulta la guía de configuración del entorno de desarrollo de Python.

Autentica y crea una instancia de un cliente

Para llamar a la API de User Invitation como una cuenta de servicio, debes usar la delegación de todo el dominio (DWD). Puedes autenticar la cuenta de servicio con las credenciales predeterminadas de la aplicación (ADC) o una clave de cuenta de servicio.

Para autenticarte como administrador sin DWD, usa las credenciales de OAuth 2.0 del usuario final con el permiso https://www.googleapis.com/auth/cloud-identity.userinvitations. Para obtener más información, consulta Usa OAuth 2.0 para aplicaciones de servidor web.

Configura la delegación de todo el dominio

Para usar la delegación de todo el dominio, debes otorgar a la cuenta de servicio la autoridad para actuar como administrador. Los registros de auditoría muestran las acciones de la cuenta de servicio como el usuario cuya identidad se usó.

Para obtener instrucciones, consulta Delega la autoridad de todo el dominio a tu cuenta de servicio.

Para autorizar la cuenta de servicio, proporciona el siguiente permiso:

  • https://www.googleapis.com/auth/cloud-identity.userinvitations

Crea una instancia de cliente

Para crear una instancia de un cliente, elige un método de autenticación. Te recomendamos que uses las credenciales predeterminadas de la aplicación (ADC) si tu código se ejecuta en Google Cloud o si usas la federación de identidades para cargas de trabajo.

ADC

from google.auth import iam
from google.auth.transport import requests
import google.auth
from google.oauth2 import service_account

INITIAL_SCOPES = ['https://www.googleapis.com/auth/iam']
CI_SCOPES = ['https://www.googleapis.com/auth/cloud-identity.userinvitations']
TOKEN_URI = "https://accounts.google.com/o/oauth2/token"

def create_delegated_credentials(
  user_email: str
) -> google.auth.credentials.Credentials:
  """Creates delegated credentials for the user.

  Args:
    user_email: The administrator email to call as.

  Returns:
    The delegated credentials for the user.
  """

  # Fetch application default credentials (ADC)
  credentials, _ = google.auth.default(scopes=INITIAL_SCOPES)

  # Populate account information
  request = requests.Request()
  credentials.refresh(request)

  # Create an IAM signer
  signer = iam.Signer(request, credentials,
                      credentials.service_account_email)

  # Create domain-wide delegated (DWD) credentials
  delegated_credentials = service_account.Credentials(
      signer=signer,
      service_account_email=credentials.service_account_email,
      token_uri=TOKEN_URI,
      scopes=CI_SCOPES,
      subject=user_email
  )

  return delegated_credentials

Clave de cuenta de servicio

from google.oauth2 import service_account
import googleapiclient.discovery

SCOPES = ['https://www.googleapis.com/auth/cloud-identity.userinvitations']
SERVICE_ACCOUNT_FILE = '/path/to/service-account-file.json'

def create_service():
  credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)
  delegated_credentials = credentials.with_subject('user@altostrat.com')

  service_name = 'cloudidentity'
  api_version = 'v1'
  service = googleapiclient.discovery.build(
    service_name,
    api_version,
    credentials=delegated_credentials)

  return service

Después de ejecutar este código, puedes comenzar a realizar llamadas a la API de User Invitation.

¿Qué sigue?