Como configurar a API Policy

Nesta página, explicamos como configurar a API Cloud Identity Policy antes de listar e receber políticas.

Instalar a biblioteca de cliente do Python

Para instalar a biblioteca de cliente Python, execute o seguinte comando:

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

Para mais informações sobre a configuração do ambiente de desenvolvimento do Python, consulte o Guia de configuração do ambiente de desenvolvimento do Python.

Ativar a API e configurar as credenciais da conta de serviço

  1. Faça login na sua Google Cloud conta do. Se você começou a usar o Google Cloud, crie uma conta para avaliar o desempenho dos nossos produtos em situações reais. Clientes novos também recebem US $300 em créditos para executar, testar e implantar cargas de trabalho.
  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.

Autenticar como uma conta de serviço com delegação em todo o domínio

Se você for um administrador que gerencia políticas de identidade ou quiser fornecer uma conta com privilégios em todo o domínio para que ela possa gerenciar políticas do Google em nome dos administradores, faça a autenticação como uma conta de serviço e conceda a ela privilégios em todo o domínio.

Para saber mais sobre como configurar a delegação em todo o domínio, consulte Controlar o acesso à API com a delegação em todo o domínio. Consulte as práticas recomendadas para reduzir os riscos de segurança associados ao uso da delegação em todo o domínio.

Depois de configurar a delegação em todo o domínio, o Application Default Credentials (ADC) poderá ser usado para autenticação. Ao usar o ADC, o código pode ser executado em um ambiente de desenvolvimento ou ambiente de produção sem mudar a forma como o aplicativo é autenticado nos serviços e nas APIs do Google Cloud. Ao inicializar as credenciais no código, especifique o endereço de e-mail em que a conta de serviço atua usando o parâmetro subject() na credencial. Verifique se o endereço de e-mail recebeu o papel Service Account User na conta de serviço (conforme descrito acima). Exemplo:

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 personificar uma conta de serviço ao usar as credenciais padrão do aplicativo, use a flag 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

Um exemplo de código detalhado para chamar a API Policy, incluindo o código de autenticação, é fornecido em Listar e receber políticas.