Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Um Bearer Token é definido no cabeçalho Authorization de cada solicitação HTTP de ação no app. Exemplo:
POST/approve?expenseId=abc123HTTP/1.1Host:your-domain.comAuthorization:Bearer AbCdEf123456Content-Type:application/x-www-form-urlencodedUser-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/1.0 (KHTML, like Gecko; Gmail Actions)confirmed=Approved
A string "AbCdEf123456" no exemplo acima é o token de autorização do portador.
É um token criptográfico produzido pelo Google.
Todos os tokens do portador enviados com ações têm o campo azp (parte autorizada) como gmail@system.gserviceaccount.com, e o campo audience especifica o domínio do remetente como um URL do formulário https://. Por exemplo, se o e-mail for de noreply@example.com, o público-alvo será https://example.com.
Se você estiver usando tokens de portador, verifique se a solicitação vem do Google
e é destinada ao domínio do remetente. Se o token não for verificado, o serviço deverá
responder à solicitação com um código de resposta HTTP 401 (Unauthorized).
Os tokens do portador fazem parte do padrão OAuth V2 e são amplamente adotados pelas APIs do Google.
Como verificar tokens do portador
Recomendamos que os serviços usem a biblioteca de cliente da API do Google de código aberto para verificar tokens de portador:
importjava.io.IOException;importjava.security.GeneralSecurityException;importjava.util.Collections;importcom.google.api.client.googleapis.auth.oauth2.GoogleIdToken;importcom.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;importcom.google.api.client.http.apache.ApacheHttpTransport;importcom.google.api.client.json.jackson2.JacksonFactory;publicclassTokenVerifier{// Bearer Tokens from Gmail Actions will always be issued to this authorized party.privatestaticfinalStringGMAIL_AUTHORIZED_PARTY="gmail@system.gserviceaccount.com";// Intended audience of the token, based on the sender's domainprivatestaticfinalStringAUDIENCE="https://example.com";publicstaticvoidmain(String[]args)throwsGeneralSecurityException,IOException{// Get this value from the request's Authorization HTTP header.// For example, for "Authorization: Bearer AbCdEf123456" use "AbCdEf123456"StringbearerToken="AbCdEf123456";GoogleIdTokenVerifierverifier=newGoogleIdTokenVerifier.Builder(newApacheHttpTransport(),newJacksonFactory()).setAudience(Collections.singletonList(AUDIENCE)).build();GoogleIdTokenidToken=verifier.verify(bearerToken);if(idToken==null||!idToken.getPayload().getAuthorizedParty().equals(GMAIL_AUTHORIZED_PARTY)){System.out.println("Invalid token");System.exit(-1);}// Token originates from Google and is targeted to a specific client.System.out.println("The token is valid");System.out.println("Token details:");System.out.println(idToken.getPayload().toPrettyString());}}
Python
importsysfromoauth2clientimportclient# Bearer Tokens from Gmail Actions will always be issued to this authorized party.GMAIL_AUTHORIZED_PARTY='gmail@system.gserviceaccount.com'# Intended audience of the token, based on the sender's domainAUDIENCE='https://example.com'try:# Get this value from the request's Authorization HTTP header.# For example, for "Authorization: Bearer AbCdEf123456" use "AbCdEf123456"bearer_token='AbCdEf123456'# Verify valid token, signed by google.com, intended for a third party.token=client.verify_id_token(bearer_token,AUDIENCE)print('Token details: %s'%token)iftoken['azp']!=GMAIL_AUTHORIZED_PARTY:sys.exit('Invalid authorized party')except:sys.exit('Invalid token')# Token originates from Google and is targeted to a specific client.print('The token is valid')
[null,null,["Última atualização 2025-08-29 UTC."],[],[],null,["# Verify Bearer Tokens\n\n| **Note:** Bearer tokens in authorization headers are not sent by default. If you require a bearer token token to be sent, request it when [registering with Google](/workspace/gmail/markup/registering-with-google).\n\nA `Bearer Token` is set in the `Authorization` header of every In-App Action HTTP Request. For example: \n\n POST /approve?expenseId=abc123 HTTP/1.1\n Host: your-domain.com\n Authorization: Bearer AbCdEf123456\n Content-Type: application/x-www-form-urlencoded\n User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/1.0 (KHTML, like Gecko; Gmail Actions)\n\n confirmed=Approved\n\nThe string \"AbCdEf123456\" in the example above is the bearer authorization token.\nThis is a cryptographic token produced by Google.\nAll bearer tokens sent with actions have the `azp` (authorized party) field as\n`gmail@system.gserviceaccount.com`, with the `audience` field specifying the sender domain as a URL of the form\n`https://`. For example, if the email is from `noreply@example.com`, the\naudience is `https://example.com`.\n\nIf using bearer tokens, verify that the request is coming from Google\nand is intended for the the sender domain. If the token doesn't verify, the service should\nrespond to the request with an HTTP response code `401 (Unauthorized)`.\n\nBearer Tokens are part of the OAuth V2 standard and widely adopted by Google APIs.\n\nVerifying Bearer Tokens\n-----------------------\n\nServices are encouraged to use the open source Google API Client library to verify Bearer tokens:\n\n- **Java** : \u003chttps://github.com/google/google-api-java-client\u003e\n- **Python** : \u003chttps://github.com/google/google-api-python-client\u003e\n- **.NET** : \u003chttps://github.com/google/google-api-dotnet-client\u003e\n\n### Java\n\n import java.io.IOException;\n import java.security.GeneralSecurityException;\n import java.util.Collections;\n\n import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;\n import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;\n import com.google.api.client.http.apache.ApacheHttpTransport;\n import com.google.api.client.json.jackson2.JacksonFactory;\n\n public class TokenVerifier {\n // Bearer Tokens from Gmail Actions will always be issued to this authorized party.\n private static final String GMAIL_AUTHORIZED_PARTY = \"gmail@system.gserviceaccount.com\";\n\n // Intended audience of the token, based on the sender's domain\n private static final String AUDIENCE = \"https://example.com\";\n\n public static void main(String[] args) throws GeneralSecurityException, IOException {\n // Get this value from the request's Authorization HTTP header.\n // For example, for \"Authorization: Bearer AbCdEf123456\" use \"AbCdEf123456\"\n String bearerToken = \"AbCdEf123456\";\n\n GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(new ApacheHttpTransport(), new JacksonFactory())\n .setAudience(Collections.singletonList(AUDIENCE))\n .build();\n\n GoogleIdToken idToken = verifier.verify(bearerToken);\n if (idToken == null || !idToken.getPayload().getAuthorizedParty().equals(GMAIL_AUTHORIZED_PARTY)) {\n System.out.println(\"Invalid token\");\n System.exit(-1);\n }\n\n // Token originates from Google and is targeted to a specific client.\n System.out.println(\"The token is valid\");\n\n System.out.println(\"Token details:\");\n System.out.println(idToken.getPayload().toPrettyString());\n }\n }\n\n### Python\n\n import sys\n\n from oauth2client import client\n\n # Bearer Tokens from Gmail Actions will always be issued to this authorized party.\n GMAIL_AUTHORIZED_PARTY = 'gmail@system.gserviceaccount.com'\n\n # Intended audience of the token, based on the sender's domain\n AUDIENCE = 'https://example.com'\n\n try:\n # Get this value from the request's Authorization HTTP header.\n # For example, for \"Authorization: Bearer AbCdEf123456\" use \"AbCdEf123456\"\n bearer_token = 'AbCdEf123456'\n\n # Verify valid token, signed by google.com, intended for a third party.\n token = client.verify_id_token(bearer_token, AUDIENCE)\n print('Token details: %s' % token)\n\n if token['azp'] != GMAIL_AUTHORIZED_PARTY:\n sys.exit('Invalid authorized party')\n except:\n sys.exit('Invalid token')\n\n # Token originates from Google and is targeted to a specific client.\n print('The token is valid')"]]