Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Nesta página, você verá como implantar um aplicativo do ambiente padrão ou flexível
do App Engine e protegê-lo com o Identity-Aware Proxy (IAP).
O guia de início rápido inclui o código de amostra de um app da Web do ambiente
padrão do App Engine que verifica o nome de um usuário conectado.
Se você planeja disponibilizar recursos de uma rede de fornecimento de conteúdo (CDN, na sigla em inglês),
consulte o guia de práticas recomendadas para
informações importantes.
Para ativar o IAP para o App Engine, você precisará destes
elementos:
Um Google Cloud projeto do console com faturamento ativado.
Se você ainda não configurou a instância do App Engine, consulte
Como implantar o App Engine
para um tutorial completo.
O IAP usa um cliente OAuth gerenciado pelo Google para autenticar usuários.
Somente os usuários da organização podem acessar o aplicativo com IAP ativado.
Se você quiser permitir o acesso de usuários de fora da sua organização, consulte Ativar o IAP para aplicativos externos.
Como ativar o IAP
Console
O cliente OAuth gerenciado pelo Google não está disponível ao ativar o IAP usando o console Google Cloud .
Arquivo de inclusão dinâmico
Se você ainda não tiver configurado a tela de consentimento do OAuth do seu projeto, precisará
fazer isso. Para configurar a tela de consentimento do OAuth, consulte
Como configurar a tela de consentimento do OAuth.
Selecione o projeto que você quer proteger com o IAP.
Marque a caixa de seleção ao lado do recurso que você quer conceder acesso.
No painel à direita, clique em Adicionar principal.
Na caixa de diálogo Adicionar membros que é exibida, insira os endereços de e-mail de grupos ou
indivíduos que terão o papel Usuário do app da Web protegido pelo IAP no projeto.
Os seguintes tipos de administradores podem ter esse papel:
Conta do Google: user@gmail.com
grupo do Google: admins@googlegroups.com
Conta de serviço: server@example.gserviceaccount.com
Domínio do Google Workspace: example.com
Inclua uma Conta do Google a que você tenha acesso.
Selecione Cloud IAP > Usuário do app da Web protegido pelo IAP na lista suspensa Papéis.
Clique em Salvar.
Ativando o IAP
Na página Identity-Aware Proxy, em APLICAÇÕES,
encontre o aplicativo a que você quer restringir
o acesso. Para ativar o IAP para um recurso,
alterne a chave para ativado ou desativado na coluna IAP.
Na janela Ativar IAP que é exibida, clique em Ativar para confirmar que você quer proteger seu recurso com o IAP. Depois disso, será necessário usar credenciais de login para todas as conexões com o balanceador de carga.
O acesso será concedido apenas às contas com o papel usuário do app da Web protegido pelo IAP no projeto.
gcloud
Antes de configurar o projeto e o IAP, você precisa de uma versão atualizada da
CLI gcloud. Para instruções sobre como instalar a CLI gcloud, consulte Instalar a CLI gcloud.
Para fazer a autenticação, use a CLI do Google Cloud e execute o comando a seguir.
gcloud auth login
Clique no URL que aparece e faça login.
Depois de fazer login, copie o código de verificação que aparece e cole-o na linha de comando.
Execute o comando a seguir para especificar o projeto que contém os aplicativos que você quer proteger com o IAP.
gcloud config set project PROJECT_ID
Para ativar o IAP, execute o comando a seguir.
gcloud iap web enable --resource-type=app-engine --versions=version
Adicione participantes que terão o papel de usuário do app da Web protegido pelo IAP ao projeto.
Substitua PRINCIPAL_IDENTIFIER pelos princípios necessários. Pode ser um
tipo de domínio, grupo, serviceAccount ou usuário. Por exemplo,
user:myemail@example.com.
Depois de ativar o IAP, será possível usar a CLI gcloud para modificar a
política de acesso do IAP usando o papel
roles/iap.httpsResourceAccessor do IAM. Saiba mais sobre como gerenciar papéis e permissões.
API
Execute o comando a seguir para preparar um arquivo settings.json.
Depois de ativar o IAP, será possível usar a CLI do Google Cloud para modificar a
política de acesso do IAP usando o papel do IAM
roles/iap.httpsResourceAccessor. Saiba mais sobre como gerenciar papéis e permissões.
Testar a autenticação do usuário
Acesse o URL do app usando uma conta do Google que você adicionou ao IAP com o papel Usuário do app da Web protegido pelo IAP, conforme descrito acima. Você precisa ter acesso irrestrito a ele.
Use uma janela anônima no Chrome para acessar o app e faça login quando solicitado. Se você tentar acessar o app com uma conta que não está autorizada com o papel Usuário do app da Web protegido pelo IAP, será exibida uma mensagem informando que você não têm acesso.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-01 UTC."],[],[],null,["# Securing App Engine apps with IAP\n\nThis page walks you through deploying an App Engine standard or flexible\nenvironment application and securing it with [Identity-Aware Proxy (IAP)](/iap/docs/concepts-overview).\nThe quickstart includes sample code for an App Engine standard\nenvironment web app that verifies a logged-in user's name.\n\nIf you plan to serve resources from a content delivery network (CDN),\nsee the [best practices guide](/iap/docs/concepts-best-practices#caching) for\nimportant information.\n\nTo secure resources not on Google Cloud, see\n[Securing on-premises apps and resources](/chrome-enterprise-premium/docs/securing-on-premises).\n\nBefore you begin\n----------------\n\nTo enable IAP for App Engine, you need the\nfollowing:\n\n- A Google Cloud console project with billing enabled.\n\nIf you don't have your App Engine instance set up already, see\n[Deploying App Engine](/build/docs/deploying-builds/deploy-appengine)\nfor a complete walkthrough.\n\nIAP uses a Google-managed OAuth client to authenticate users.\nOnly users within the organization can access the IAP-enabled application.\nIf you want to allow access to users outside of your organization, see [Enable IAP for external applications](/iap/docs/custom-oauth-configuration).\n| **Note:** The ability to authenticate users with a Google-managed OAuth client is available in [Preview](/products#product-launch-stages).\n\nEnabling IAP\n------------\n\n### Console\n\nThe Google-managed OAuth client is not available when enabling IAP using the Google Cloud console.\n\n\nDynamic include file\n\n\nIf you haven't configured your project's OAuth consent screen, you'll be\nprompted to do so. To configure your OAuth consent screen, see\n[Setting up your OAuth consent screen](https://support.google.com/cloud/answer/10311615).\n\n### Setting up IAP access\n\n1. Go to the [Identity-Aware Proxy page](https://console.cloud.google.com/security/iap). \n [Go to the Identity-Aware Proxy page](https://console.cloud.google.com/security/iap)\n2. Select the project you want to secure with IAP.\n3. Select the checkbox next to the resource you want to grant access to.\n4. On the right side panel, click **Add principal**.\n5. 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.\n\n The following kinds of principals can have this role:\n - **Google Account**: user@gmail.com\n - **Google Group**: admins@googlegroups.com\n - **Service account**: server@example.gserviceaccount.com\n - **Google Workspace domain**: example.com\n\n Make sure to add a Google Account that you have access to.\n6. Select **Cloud IAP \\\u003e IAP-secured Web App User** from the **Roles** drop-down list.\n7. Click **Save**.\n\n### Turning on IAP\n\n1. On the **Identity-Aware Proxy** page, under **APPLICATIONS** , find the application you want to restrict access to. To turn on IAP for a resource, toggle the on/off switch in the **IAP** column. \n2. 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.\n\n\u003cbr /\u003e\n\n### gcloud\n\nBefore you set up your project and IAP, you need an up-to-date version of the\ngcloud CLI. For instructions on how to install the gcloud CLI, see [Install the gcloud CLI](/sdk/downloads).\n\n1. To authenticate, use the Google Cloud CLI and run the following command. \n\n gcloud auth login\n\n2. Click the URL that appears and sign in.\n3. After you sign in, copy the verification code that appears and paste it in the command line.\n4. Run the following command to specify the project that contains the applications that you want to protect with IAP. \n\n gcloud config set project \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e\n\n5. To enable IAP, run the following command. \n\n gcloud iap web enable --resource-type=app-engine --versions=\u003cvar translate=\"no\"\u003eversion\u003c/var\u003e\n\n6. Add principals who should have the IAP-secured Web App user role to the project. \n\n gcloud projects add-iam-policy-binding \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e \\\n --member=\u003cvar translate=\"no\"\u003ePRINCIPAL_IDENTIFIER\u003c/var\u003e \\\n --role=roles/iap.httpsResourceAccessor\n\n - Replace \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e with your project ID.\n - Replace \u003cvar translate=\"no\"\u003ePRINCIPAL_IDENTIFIER\u003c/var\u003e with the necessary principals. This can be a type of domain, group, serviceAccount, or user. For example, `user:myemail@example.com`.\n\nAfter you enable IAP, you can use the gcloud CLI to modify the\nIAP access policy using the IAM role\n`roles/iap.httpsResourceAccessor`. Learn more about\n[managing roles and permissions](/iam/docs/granting-changing-revoking-access).\n\n### API\n\n1. Run the following command to prepare a `settings.json` file.\n\n ```\n cat \u003c\u003c EOF \u003e settings.json\n {\n \"iap\":\n {\n \"enabled\":true\n }\n }\n EOF\n ```\n\n \u003cbr /\u003e\n\n2. Run the following command to enable IAP.\n\n ```\n curl -X PATCH \\\n -H \"Authorization: Bearer $(gcloud auth print-access-token)\" \\\n -H \"Accept: application/json\" \\\n -H \"Content-Type: application/json\" \\\n -d @settings.json \\\n \"https://appengine.googleapis.com/v1/apps/PROJECT_ID?updateMask=iap\"\n ```\n\n \u003cbr /\u003e\n\nAfter you enable IAP, you can use the Google Cloud CLI to modify the\nIAP access policy using the IAM role\n`roles/iap.httpsResourceAccessor`. Learn more about\n[managing roles and permissions](/iam/docs/granting-changing-revoking-access).\n| **Note:** When a App Engine application consists of multiple services, in order to make some services publicly-accessible and keep others restricted, enable IAP on the entire application, then grant the **IAP-secured Web App User** role to \\`allUsers\\` or \\`allAuthenticatedUsers\\` on the services that should be publicly-accessible.\n| **Role-based access:** If you're a project owner, you may think that you get automatic access to the app. That is not the case as only accounts with the **IAP-secured Web App User** role on this project will be given access. Imagine you're in corporate IT implementing IAP access to the HR payroll system. In most scenarios, only the staff on the Payroll team should have access to the app. This is one of the reasons why role-based access is more secure. The owner (or editor, etc.) of a project can manage all aspects of the project but doesn't automatically get app access.\n\nTest user authentication\n------------------------\n\n1. Access the app URL from a Google account that you added to\n IAP with the **IAP-secured Web App User** role\n as described above. You should have unrestricted access to the app.\n\n2. Use an incognito window in Chrome to access the app and sign in when\n prompted. If you try to access the app with an account that isn't authorized\n with the **IAP-secured Web App User** role, you'll see a message\n saying that you don't have access.\n\nNext steps\n----------\n\n- Set richer context rules by [applying access levels](/chrome-enterprise-premium/docs/access-levels).\n- See access requests by [enabling Cloud Audit Logs](/chrome-enterprise-premium/docs/audit-logs).\n- Learn more about [IAP](/iap/docs/concepts-overview).\n- Learn about [getting the user's identity](/iap/docs/identity-howto) and develop your own [App Engine](/appengine) app."]]