En este documento se describe cuándo y cómo personalizar una configuración de OAuth para Identity-Aware Proxy (IAP).
IAP usa un cliente de OAuth gestionado por Google para autenticar a los usuarios.
El cliente OAuth gestionado por Google restringe el acceso a los usuarios de la misma organización cuando acceden a aplicaciones habilitadas para IAP a través de un navegador.
Cuándo usar una configuración de OAuth personalizada
Debes usar una configuración de OAuth personalizada para hacer lo siguiente:
- Para permitir el acceso a aplicaciones habilitadas para IAP a usuarios ajenos a la organización.
- Para mostrar la información de tu marca durante la autenticación.
- Para habilitar el acceso programático a tu aplicación.
Cuando personalizas la configuración de OAuth, debes configurar la pantalla de consentimiento de OAuth. Para ello, la información de marca de tu aplicación debe pasar por el proceso de verificación de Google. Para obtener más información sobre el proceso de verificación, consulta Configurar la pantalla de consentimiento de OAuth.
Eres responsable de crear y gestionar las credenciales de un cliente de OAuth personalizado. Esto incluye almacenar el secreto de cliente de forma segura y compartirlo con los usuarios autorizados cuando sea necesario.
Comparación entre el cliente de OAuth gestionado por Google y el cliente de OAuth personalizado
Los clientes de OAuth gestionados por Google no pueden acceder de forma programática a aplicaciones protegidas por IAP. Sin embargo, se puede seguir accediendo de forma programática a las aplicaciones protegidas por IAP que usen el cliente de OAuth gestionado por Google mediante otro cliente de OAuth configurado a través del ajuste programmatic_clients o de un JWT de cuenta de servicio.
En la siguiente tabla se comparan el cliente de OAuth gestionado por Google y un cliente de OAuth personalizado.
| Cliente de OAuth gestionado por Google | Cliente de OAuth personalizado | |
|---|---|---|
| Usuarios | Solo para uso interno | Internas y externas |
| Brand | Google Cloud marca | Marca propiedad del cliente |
| Configuración de OAuth | Configurado por Google | Configuración del cliente |
| Credenciales de OAuth | Gestionado por Google | Gestionada por el cliente |
| Acceso a aplicaciones | Solo flujo del navegador | Flujo del navegador y acceso programático |
Habilitar IAP con una configuración de cliente de OAuth personalizada
En las siguientes secciones se explica cómo habilitar las compras en la aplicación mediante una configuración de cliente OAuth personalizada para diferentes recursos.
App Engine
Consola
Si no has configurado la pantalla de consentimiento de OAuth de tu proyecto, se te pedirá que lo hagas. Para configurar la pantalla de consentimiento de OAuth, consulta el artículo Configurar la pantalla de consentimiento de OAuth.
Configurar el acceso a IAP
-
Ve a la página Identity-Aware Proxy.
Ve a la página Identity-Aware Proxy - Selecciona el proyecto que quieras proteger con IAP.
- Seleccione la casilla situada junto al recurso al que quiera conceder acceso.
- En el panel lateral de la derecha, haz clic en Añadir principal.
-
En el cuadro de diálogo Añadir principales que aparece, introduce las direcciones de correo de los grupos o las personas que deban tener el rol Usuario de aplicaciones web protegidas mediante IAP en el proyecto.
Los siguientes tipos de principales pueden tener este rol:
- Cuenta de Google: usuario@gmail.com
- Grupo de Google: admins@googlegroups.com
- Cuenta de servicio: servidor@example.gserviceaccount.com
- Dominio de Google Workspace: example.com
Asegúrate de añadir una cuenta de Google a la que tengas acceso.
- En la lista desplegable Roles, selecciona Cloud IAP > IAP-secured Web App User (Cloud IAP > Usuario de aplicación web protegida con IAP).
- Haz clic en Guardar.
Activando IAP
-
En la página Identity-Aware Proxy, en APLICACIONES, busca la aplicación a la que quieras restringir el acceso. Para activar IAP en un recurso, haz lo siguiente:
- En la ventana Activar IAP que aparece, haz clic en Activar para confirmar que quieres que IAP proteja tu recurso. Una vez que hayas activado IAP, se requerirán credenciales de inicio de sesión para todas las conexiones con tu balanceador de carga. Solo se concederá acceso a las cuentas que tengan el rol Usuario de aplicaciones web protegidas mediante IAP en el proyecto.
gcloud
Before you set up your project and IAP, you need an up-to-date version of gcloud CLI. For instructions on how to install the gcloud CLI, see Install the gcloud CLI.
-
To authenticate, use the Google Cloud CLI and run the following command.
gcloud auth login - To sign in, follow the URL that appears.
- After you sign in, copy the verification code that appears and paste it in the command line.
-
Run the following command to specify the project that contains the resource that you want to protect with IAP.
gcloud config set project PROJECT_ID - Follow the instructions in Creating OAuth clients for IAP to configure the OAuth consent screen and create the OAuth client.
- Save the OAuth client ID and secret.
-
To enable IAP, run the following command.
gcloud iap web enable \ --oauth2-client-id=CLIENT_ID \ --oauth2-client-secret=CLIENT_SECRET \ --resource-type=app-engine
After you enable IAP, you can use the gcloud CLI to modify the
IAP access policy using the IAM role
roles/iap.httpsResourceAccessor. Learn more about
managing roles and permissions.
API
Sigue las instrucciones de Crear clientes de OAuth para compras en aplicaciones para configurar la pantalla de consentimiento de OAuth y crear el cliente de OAuth.
Guarda el ID y el secreto de cliente de OAuth.
Ejecuta el siguiente comando para preparar un archivo
settings.json.cat << EOF > settings.json { "iap": { "enabled": true, "oauth2ClientId": "CLIENT_ID", "oauth2ClientSecret":" CLIENT_SECRET" } } EOFEjecuta el siguiente comando para habilitar IAP.
curl -X PATCH \ -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -d @settings.json \ "https://appengine.googleapis.com/v1/apps/PROJECT_ID?updateMask=iap"
Una vez que hayas habilitado IAP, puedes usar la CLI de Google Cloud para modificar la política de acceso de IAP con el rol de gestión de identidades y accesos roles/iap.httpsResourceAccessor. Más información sobre cómo gestionar roles y permisos
Compute Engine
Consola
If you haven't configured your project's OAuth consent screen, you'll be prompted to do so. To configure your OAuth consent screen, see Setting up your OAuth consent screen.
If you are running GKE clusters version 1.24 or later, you can configure
IAP and GKE by using the Kubernetes Gateway API. To do so, complete
the following steps and then follow the instructions in
Configure IAP.
Do not configure BackendConfig.
Setting up IAP access
-
Go to the
Identity-Aware Proxy page.
Go to the Identity-Aware Proxy page - Select the project you want to secure with IAP.
-
Select the checkbox next to the resource you want to grant access to.
If you don't see a resource, ensure that the resource is created and that the BackendConfig Compute Engine ingress controller is synced.
To verify that the backend service is available, run the following gcloud command:
gcloud compute backend-services list - On the right side panel, click Add principal.
-
In the Add principals dialog that appears, enter the email addresses of groups or
individuals who should have the IAP-secured Web App User role for the project.
The following kinds of principals can have this role:
- Google Account: user@gmail.com
- Google Group: admins@googlegroups.com
- Service account: server@example.gserviceaccount.com
- Google Workspace domain: example.com
Make sure to add a Google Account that you have access to.
- Select Cloud IAP > IAP-secured Web App User from the Roles drop-down list.
- Click Save.
Turning on IAP
-
On the Identity-Aware Proxy page, under APPLICATIONS,
find the load balancer that serves the instance group you want to restrict
access to. To turn on IAP for a resource,
To enable IAP:- At least one protocol in the load balancer frontend configuration must be HTTPS. Learn about setting up a load balancer.
-
You need the
compute.backendServices.update,clientauthconfig.clients.create,clientauthconfig.clients.update, andclientauthconfig.clients.getWithSecretpermissions. These permissions are granted by roles, such as the Project Editor role. To learn more, see Managing access to IAP-secured resources.
- In the Turn on IAP window that appears, click Turn On to confirm that you want IAP to secure your resource. After you turn on IAP, it requires login credentials for all connections to your load balancer. Only accounts with the IAP-Secured Web App User role on the project will be given access.
gcloud
Before you set up your project and IAP, you need an up-to-date version of the gcloud CLI. For instructions on how to install the gcloud CLI, see Install the gcloud CLI.
-
To authenticate, use the Google Cloud CLI and run the following command.
gcloud auth login - To sign in, follow the URL that appears.
- After you sign in, copy the verification code that appears and paste it in the command line.
-
Run the following command to specify the project that contains the resource that you want to protect with IAP.
gcloud config set project PROJECT_ID
- Follow the instructions in Creating OAuth clients for IAP. to configure the OAuth consent screen and create the OAuth client.
- Save the OAuth client ID and secret.
-
To enable IAP, run either the globally or regionally scoped command.
Global scope Regional scopegcloud compute backend-services update BACKEND_SERVICE_NAME \ --global \ --iap=enabled,oauth2-client-id=CLIENT_ID,oauth2-client-secret=CLIENT_SECRETgcloud compute backend-services update BACKEND_SERVICE_NAME \ --region REGION_NAME \ --iap=enabled,oauth2-client-id=CLIENT_ID,oauth2-client-secret=CLIENT_SECRET
After you enable IAP, you can use the gcloud CLI to modify the
IAP access policy using the IAM role
roles/iap.httpsResourceAccessor. Learn more about
managing roles and permissions.
API
Follow the instructions in Creating OAuth clients for IAP to configure the OAuth consent screen and create the OAuth client.
Save the OAuth client ID and secret.
Run the following command to prepare a
settings.jsonfile.cat << EOF > settings.json { "iap": { "enabled": true, "oauth2ClientId": "CLIENT_ID", "oauth2ClientSecret": "CLIENT_SECRET" } } EOFRun the following command to enable IAP.
curl -X PATCH \ -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -d @settings.json \ "https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/REGION/backendServices/BACKEND_SERVICE_NAME"
After you enable IAP, you can use the gcloud CLI to modify the
IAP access policy using the IAM role
roles/iap.httpsResourceAccessor. Learn more about
managing roles and permissions.
Cloud Run
Consola
Si no has configurado la pantalla de consentimiento de OAuth de tu proyecto, se te pedirá que lo hagas. Para configurar la pantalla de consentimiento de OAuth, consulta Configurar la pantalla de consentimiento de OAuth.
Configurar el acceso a IAP
- Abre la página Identity-Aware Proxy.
Ir a Identity-Aware Proxy - Selecciona el proyecto que quieras proteger con IAP.
- En Aplicaciones, marca la casilla situada junto al servicio de backend del balanceador de carga al que quieras añadir miembros.
- En el panel de la derecha, haz clic en Añadir miembro.
En el cuadro de diálogo Añadir miembros, introduce las cuentas de los grupos o usuarios que deban tener el rol Usuario de aplicaciones web protegidas mediante IAP en el proyecto. Pueden ser miembros los siguientes tipos de cuentas:
- Cuenta de Google: usuario@gmail.com. También puede ser una cuenta de Google Workspace, como usuario@google.com u otro dominio de Google Workspace.
- Grupo de Google: admins@googlegroups.com
- Cuenta de servicio: servidor@example.gserviceaccount.com
- Dominio de Google Workspace: example.com
Selecciona Cloud IAP > Usuario de aplicaciones web protegidas mediante IAP en la lista Roles.
Haz clic en Guardar.
Activando IAP
- En la página de compras en la aplicación, en Aplicaciones, busca el servicio de backend del balanceador de carga al que quieras restringir el acceso. Haz clic en el interruptor IAP para habilitar las compras en la aplicación en un recurso.
- En la ventana Activar IAP que aparece, haz clic en Activar para confirmar que quieres que IAP proteja tu recurso. Después de activar IAP, se requieren credenciales de inicio de sesión para todas las conexiones con tu balanceador de carga. Solo se concederá acceso a las cuentas que tengan el rol Usuario de aplicaciones web protegidas mediante IAP en el proyecto.
Para autorizar a IAP a enviar tráfico al servicio de backend de Cloud Run, sigue las instrucciones que se indican en el artículo Añadir principales a un servicio para añadir el siguiente principal y rol.
- Principal:
service-[PROJECT-NUMBER]@gcp-sa-iap.iam.gserviceaccount.com - Rol: Invocador de Cloud Run
- Principal:
gcloud
- Sigue las instrucciones de Crear clientes de OAuth para compras en aplicaciones para configurar la pantalla de consentimiento de OAuth y crear el cliente de OAuth.
- Guarda el ID y el secreto de cliente de OAuth.
- Si aún no lo has hecho, crea una cuenta de servicio ejecutando el siguiente comando. Si ya has creado una cuenta de servicio, al ejecutar el comando no se crearán cuentas de servicio duplicadas.
gcloud beta services identity create \ --service=iap.googleapis.com --project=PROJECT_ID - Concede el permiso de invocador a la cuenta de servicio que has creado en el paso anterior ejecutando el siguiente comando.
gcloud run services add-iam-policy-binding SERVICE-NAME \ --member='serviceAccount:service-PROJECT-NUMBER@gcp-sa-iap.iam.gserviceaccount.com' \ --role='roles/run.invoker' Habilita IAP ejecutando el comando de ámbito global o regional, en función de si el servicio de backend del balanceador de carga es global o regional. Usa el ID y el secreto de cliente de OAuth del paso anterior.
Ámbito global
gcloud compute backend-services update BACKEND_SERVICE_NAME \ --global \ --iap=enabled,oauth2-client-id=CLIENT_ID,oauth2-client-secret=CLIENT_SECRETÁmbito regional
Sustituye lo siguiente:gcloud compute backend-services update BACKEND_SERVICE_NAME \ --region REGION_NAME \ --iap=enabled,oauth2-client-id=CLIENT_ID,oauth2-client-secret=CLIENT_SECRET- BACKEND_SERVICE_NAME: el nombre del servicio de backend.
- CLIENT_ID: el ID de cliente de OAuth del paso anterior.
- CLIENT_SECRET: el secreto de cliente de OAuth del paso anterior.
- REGION_NAME: la región en la que quieres habilitar IAP.
Una vez que hayas habilitado IAP, puedes usar la CLI de Google Cloud para modificar la política de acceso de IAP con el rol roles/iap.httpsResourceAccessor de Gestión de Identidades y Accesos. Consulta más información sobre cómo gestionar roles y permisos.
Google Kubernetes Engine
Consola
If you haven't configured your project's OAuth consent screen, you'll be prompted to do so. To configure your OAuth consent screen, see Setting up your OAuth consent screen.
If you are running GKE clusters version 1.24 or later, you can configure
IAP and GKE by using the Kubernetes Gateway API. To do so, complete
the following steps and then follow the instructions in
Configure IAP.
Do not configure BackendConfig.
Setting up IAP access
-
Go to the
Identity-Aware Proxy page.
Go to the Identity-Aware Proxy page - Select the project you want to secure with IAP.
-
Select the checkbox next to the resource you want to grant access to.
If you don't see a resource, ensure that the resource is created and that the BackendConfig Compute Engine ingress controller is synced.
To verify that the backend service is available, run the following gcloud command:
gcloud compute backend-services list - On the right side panel, click Add principal.
-
In the Add principals dialog that appears, enter the email addresses of groups or
individuals who should have the IAP-secured Web App User role for the project.
The following kinds of principals can have this role:
- Google Account: user@gmail.com
- Google Group: admins@googlegroups.com
- Service account: server@example.gserviceaccount.com
- Google Workspace domain: example.com
Make sure to add a Google Account that you have access to.
- Select Cloud IAP > IAP-secured Web App User from the Roles drop-down list.
- Click Save.
Turning on IAP
-
On the Identity-Aware Proxy page, under APPLICATIONS,
find the load balancer that serves the instance group you want to restrict
access to. To turn on IAP for a resource,
To enable IAP:- At least one protocol in the load balancer frontend configuration must be HTTPS. Learn about setting up a load balancer.
-
You need the
compute.backendServices.update,clientauthconfig.clients.create,clientauthconfig.clients.update, andclientauthconfig.clients.getWithSecretpermissions. These permissions are granted by roles, such as the Project Editor role. To learn more, see Managing access to IAP-secured resources.
- In the Turn on IAP window that appears, click Turn On to confirm that you want IAP to secure your resource. After you turn on IAP, it requires login credentials for all connections to your load balancer. Only accounts with the IAP-Secured Web App User role on the project will be given access.
GKE
Configura BackendConfig
Si ejecutas clústeres de GKE de la versión 1.24 o posterior, puedes configurar el IAP y GKE con la API de Kubernetes Gateway. Consulta Configura IAP para obtener instrucciones.
Sigue las instrucciones que se indican en Cómo crear clientes de OAuth para IAP para configurar la pantalla de consentimiento de OAuth y crear el cliente de OAuth.
Crea un Secreto de Kubernetes para unir el cliente de OAuth.
Reemplaza lo siguiente:kubectl create secret generic MY_SECRET --from-literal=client_id=CLIENT_ID \ --from-literal=client_secret=CLIENT_SECRET
MY_SECRET: Es el nombre del Secret que se creará.CLIENT_ID: El ID de cliente de OAuthCLIENT_SECRET: El secreto del cliente de OAuth
Deberías recibir una confirmación, como el siguiente resultado, de que el Secret se creó correctamente:
secret "MY_SECRET" created
Agrega las credenciales de OAuth a BackendConfig.
apiVersion: cloud.google.com/v1 kind: BackendConfig metadata: name: CONFIG_DEFAULT namespace: my-namespace spec: iap: enabled: true oauthclientCredentials: secretName: MY_SECRETPara habilitar IAP, asocia los puertos de servicio con tu BackendConfig. Consulta Asocia un BackendConfig con el Ingress. Una forma de establecer esta asociación es hacer que todos los puertos del servicio sean predeterminados para tu BackendConfig, lo que puedes hacer si agregas la siguiente anotación a tu recurso de servicio:
metadata: annotations: beta.cloud.google.com/backend-config: '{"default": "CONFIG_DEFAULT"}}'
Después de habilitar IAP, puedes usar gcloud CLI para modificar la política de acceso de IAP con el rol de IAM roles/iap.httpsResourceAccessor. Obtén más información sobre cómo administrar funciones y permisos.
Soluciona problemas
Si el secretName al que te refieres no existe o no está estructurado correctamente, aparecerá uno de los siguientes mensajes de error:
BackendConfig default/config-default is not valid: error retrieving secret "foo": secrets "foo" not found.Para resolver este error, asegúrate de haber creado el Secret de Kubernetes correctamente, como se describe en el paso 2.BackendConfig default/config-default is not valid: secret "foo" missing client_secret data.Para solucionar este error, asegúrate de haber creado las credenciales de OAuth correctamente. Además, asegúrate de haber hecho referencia a las clavesclient_idyclient_secretcorrectas.