Configura la API de Policy
En esta página, se explica cómo configurar la API de Cloud Identity Policy antes de enumerar 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
- Accede a tu Google Cloud cuenta de. 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.
-
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 theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Cloud Identity API.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. 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.-
Create a service account:
-
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. -
In the Google Cloud console, go to the Create service account page.
Go to Create service account - Select your project.
-
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. - Click Create and continue.
-
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.
- Click Continue.
-
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.
-
Click Done to finish creating the service account.
-
Ensure that you have the Create Service Accounts IAM role
(
-
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 theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Cloud Identity API.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. 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.-
Create a service account:
-
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. -
In the Google Cloud console, go to the Create service account page.
Go to Create service account - Select your project.
-
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. - Click Create and continue.
-
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.
- Click Continue.
-
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.
-
Click Done to finish creating the service account.
-
Ensure that you have the Create Service Accounts IAM role
(
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 cuenta de servicio y otorgarle los privilegios para todo el dominio.
Para obtener detalles sobre la configuración de 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 de todo el dominio.
Después de configurar la delegación de 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 el 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 la función Service Account User en la cuenta de servicio (como se describió anteriormente).
Por ejemplo:
Importante: Los alcances de OAuth especificados en el código de tu aplicación que se usan para crear credenciales delegadas deben estar presentes en la lista de alcances autorizados para la delegación de todo el dominio en la Consola del administrador de Google. Un alcance más amplio o más permisivo no funcionará. Si la aplicación solicita un permiso para crear credenciales delegadas que no está autorizado en la delegación de todo el dominio, la aplicación recibe un
unauthorized_clienterror.
Python
AUTH_SCOPES = ['https://www.googleapis.com/auth/iam']
# The read and write scope of the API. Note that you must authorize the
# exact same scope for domain-wide delegation in the Google Admin Console.
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 la identidad de una cuenta de servicio cuando usas 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 Enumera y obtén políticas, se proporciona un código de muestra detallado para llamar a la API de Policy, incluido el código de autenticación.