Configura la API de Policy

En esta página, se explica cómo configurar la API de Cloud Identity Policy antes de listar y obtener políticas.

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 absly-py

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

Habilita la API y configura las credenciales de la cuenta de servicio

  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. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Identity API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  5. 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. In the Service account users role field, enter the identifier for the principal that will attach the service account to other resources, such as Compute Engine instances.

      This is typically the email address for a Google Account.

    9. Click Done to finish creating the service account.

  6. 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

  7. Verify that billing is enabled for your Google Cloud project.

  8. Enable the Cloud Identity API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  9. 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. In the Service account users role field, enter the identifier for the principal that will attach the service account to other resources, such as Compute Engine instances.

      This is typically the email address for a Google Account.

    9. Click Done to finish creating the service account.

Autentica como una cuenta de servicio con delegación de todo el dominio

Si eres un administrador que gestiona políticas de identidad, o si deseas proporcionar una cuenta con privilegios de todo el dominio para que pueda administrar las políticas de Google en nombre de los administradores, debes autenticarte como una cuenta de servicio y, luego, otorgarle privilegios para todo el dominio.

Para obtener detalles sobre cómo configurar la delegación de todo el dominio, consulta Controla el acceso a la API con la delegación de todo el dominio. Revisa las prácticas recomendadas para mitigar los riesgos de seguridad asociados con el uso de la delegación en todo el dominio.

Después de configurar la delegación en todo el dominio, se pueden usar las credenciales predeterminadas de la aplicación (ADC) para la autenticación. Cuando usas ADC, el código puede ejecutarse en un entorno de producción o de desarrollo sin cambiar la forma en que la aplicación se autentica en los servicios y las APIs de Google Cloud. Cuando inicialices las credenciales en tu código, especifica la dirección de correo electrónico en la que actúa la cuenta de servicio con el parámetro subject() en la credencial. Asegúrate de que la dirección de correo electrónico tenga el rol Service Account User en la cuenta de servicio (como se describió anteriormente). Por ejemplo:

Python

AUTH_SCOPES = ['https://www.googleapis.com/auth/iam']
# The read and write scope of the API. Note that you must provide the
# required scope to the service account while setting up domain-wide 
# delegation.
POLICY_SCOPES = ['https://www.googleapis.com/auth/cloud-identity.policies']
TOKEN_URI = "https://accounts.google.com/o/oauth2/token"

_ADMIN_EMAIL = flags.DEFINE_string(
    name='admin_email',
    default=None,
    help='Administrator email to call as',
    required=True,
)

# Fetch application default credentials (ADC)
credentials, _ = google.auth.default(scopes=AUTH_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=POLICY_SCOPES,
    subject=_ADMIN_EMAIL.value
)

Para suplantar una cuenta de servicio cuando se usan las credenciales predeterminadas de la aplicación, usa la marca impersonate-service-account.

Shell

gcloud auth application-default login --impersonate-service-account=<service_account_email>
--scopes=https://www.googleapis.com/auth/iam,https://www.googleapis.com/auth/cloud-identity.policies

En Cómo enumerar y obtener políticas, se proporciona un código de muestra detallado para llamar a la API de Policy, incluido el código para la autenticación.