Como acessar recursos que não são do Google de maneira programática
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Este artigo mostra como acessar um recurso protegido pelo Identity-Aware Proxy (IAP) de maneira programática usando identidades externas.
Há várias situações em que convém fazer isso, como as seguintes:
Seu aplicativo de front-end usa o Identity Platform diretamente. O servidor da API de back-end foi criado usando o App Engine e protegido pelo IAP usando identidades externas.
Seu aplicativo foi projetado para ser usado em um ambiente de navegador não tradicional, como no Android, iOS ou linha de comando, em que não é possível usar o redirecionamento do navegador para autenticar usuários.
Para acessar um recurso de maneira programática usando um token de ID, siga estas etapas:
Recupere o token de ID do usuário.
Node.js
Verifique se o usuário está conectado. O código abaixo mostra um exemplo simples de login de usuário com e-mail e senha:
// If signing in using project-level email/password IdP.// auth.tenantId = null; // This is null by default.// For signing in to a specific tenant using email/password.auth.tenantId='myTenantId';auth.signInWithEmailAndPassword(email,password).then((user)=>{// User signed in. ID token can now be retrieved.}).catch((error)=>{// Handler error.});
Depois, recupere um token de ID no objeto user:
user.getIdToken().then((idToken)=>{// idToken is now available and can be sent to API server.}).catch((error)=>{// Handler error.});
REST
Chame signInWithPassword para retornar um token de ID na resposta:
curl 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=API-KEY' \
-H 'Content-Type: application/json' \
--data-binary '{
"email":"EMAIL",
"password":"PASSWORD",
"returnSecureToken":true,
"tenantId":"TENANT-ID" # Only used in multi-tenancy
}'
Inclua o token de ID no cabeçalho de autorização ao chamar um endpoint protegido pelo IAP.
[[["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-08-18 UTC."],[[["\u003cp\u003eThis guide demonstrates how to programmatically access resources secured by Identity-Aware Proxy (IAP) using external identities.\u003c/p\u003e\n"],["\u003cp\u003eIt covers scenarios where direct Identity Platform integration or non-browser environments necessitate programmatic access, like Android, iOS, or command-line interfaces.\u003c/p\u003e\n"],["\u003cp\u003eYou can authenticate with a service account JWT, which has its own dedicated instructions, or by using an ID token as described in this document.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves retrieving a user's ID token, using methods like email/password sign-in, and then including this token in the authorization header when calling IAP-protected endpoints.\u003c/p\u003e\n"],["\u003cp\u003eThe ID Token can be retrieved from the user object after they have signed in, and the document shows how to retrieve it through Node.js and REST examples.\u003c/p\u003e\n"]]],[],null,["# Accessing non-Google resources programmatically\n\nThis article shows you how to programmatically access a resource protected by\nIdentity-Aware Proxy (IAP) using external identities.\n\nThere are several situations where you might want to do this:\n\n- Your frontend application leverages Identity Platform directly. Your\n backend API server is built using App Engine, and protected\n by IAP using external identities.\n\n- Your application is designed for use in a non-traditional browser environment,\n such as on Android, iOS, or the command-line, where using a browser\n redirect to authenticate users is infeasible.\n\nAccessing resources\n-------------------\n\nTo access a resource programmatically using a service account JWT, see\n[Authenticating with a service account JWT](/iap/docs/authentication-howto#authenticating_with_a_service_account_jwt).\n\nTo access a resource programmatically using an ID token, follow these steps:\n\n1. Retrieve the user's ID token.\n\n ### Node.js\n\n Ensure the user is signed in. The code below shows a simple example\n of signing in a user with an email and password: \n\n // If signing in using project-level email/password IdP.\n // auth.tenantId = null; // This is null by default.\n // For signing in to a specific tenant using email/password.\n auth.tenantId = 'myTenantId';\n auth.signInWithEmailAndPassword(email, password)\n .then((user) =\u003e {\n // User signed in. ID token can now be retrieved.\n })\n .catch((error) =\u003e {\n // Handler error.\n });\n\n You can then retrieve an ID token on the `user` object: \n\n user.getIdToken()\n .then((idToken) =\u003e {\n // idToken is now available and can be sent to API server.\n })\n .catch((error) =\u003e {\n // Handler error.\n });\n\n ### REST\n\n Calling `signInWithPassword` returns an ID token in the response: \n\n ```restructuredtext\n curl 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=API-KEY' \\\n -H 'Content-Type: application/json' \\\n --data-binary '{\n \"email\":\"EMAIL\",\n \"password\":\"PASSWORD\",\n \"returnSecureToken\":true,\n \"tenantId\":\"TENANT-ID\" # Only used in multi-tenancy\n }'\n ```\n2. Include the ID token in the authorization header when calling\n an endpoint protected by IAP.\n\n ```text\n curl -H \"Authorization: Bearer GCIP-ID-TOKEN\" \"https://example.appspot.com/api\"\n ```"]]