Si una suscripción de envío usa autenticación, el El servicio de Pub/Sub firma un JWT y lo envía en el encabezado de autorización de la solicitud de envío. El JWT incluye reclamaciones y una firma.
Los suscriptores pueden validar el JWT y verificar lo siguiente:
- Los reclamos son precisos.
- El servicio de Pub/Sub firmó las reclamaciones.
Si los suscriptores usan un firewall, no pueden recibir solicitudes de envío. Para recibir solicitudes de envío, debes desactivar el firewall y verificar el JWT.
Antes de comenzar
- Obtén más información sobre las suscripciones.
- Obtén información sobre cómo funcionan las suscripciones de envío.
- Crea una suscripción de envío.
Formato JWT
El JWT es un JWT de OpenIDConnect que consta de un encabezado conjunto de declaraciones y firma. El servicio de Pub/Sub codifica el JWT como una cadena base64 con delimitadores de punto.
Por ejemplo, el siguiente encabezado de autorización incluye un JWT codificado:
"Authorization" : "Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjdkNjgwZDhjNzBkNDRlOTQ3MTMzY2JkNDk5ZWJjMWE2MWMzZDVh YmMiLCJ0eXAiOiJKV1QifQ.eyJhdWQiOiJodHRwczovL2V4YW1wbGUuY29tIiwiYXpwIjoiMTEzNzc0M jY0NDYzMDM4MzIxOTY0IiwiZW1haWwiOiJnYWUtZ2NwQGFwcHNwb3QuZ3NlcnZpY2VhY2NvdW50LmNvb SIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJleHAiOjE1NTAxODU5MzUsImlhdCI6MTU1MDE4MjMzNSwia XNzIjoiaHR0cHM6Ly9hY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTEzNzc0MjY0NDYzMDM4MzIxO TY0In0.QVjyqpmadTyDZmlX2u3jWd1kJ68YkdwsRZDo-QxSPbxjug4ucLBwAs2QePrcgZ6hhkvdc4UHY 4YF3fz9g7XHULNVIzX5xh02qXEH8dK6PgGndIWcZQzjSYfgO-q-R2oo2hNM5HBBsQN4ARtGK_acG-NGG WM3CQfahbEjZPAJe_B8M7HfIu_G5jOLZCw2EUcGo8BvEwGcLWB2WqEgRM0-xt5-UPzoa3-FpSPG7DHk7 z9zRUeq6eB__ldb-2o4RciJmjVwHgnYqn3VvlX9oVKEgXpNFhKuYA-mWh5o7BCwhujSMmFoBOh6mbIXF cyf5UiVqKjpqEbqPGo_AvKvIQ9VTQ"
El encabezado y el conjunto de reclamos son strings de JSON. Una vez decodificados, toman el siguiente formato:
{"alg":"RS256","kid":"7d680d8c70d44e947133cbd499ebc1a61c3d5abc","typ":"JWT"} { "aud":"https://example.com", "azp":"113774264463038321964", "email":"gae-gcp@appspot.gserviceaccount.com", "sub":"113774264463038321964", "email_verified":true, "exp":1550185935, "iat":1550182335, "iss":"https://accounts.google.com" }
Los tokens adjuntos a las solicitudes enviadas a los extremos de envío pueden tener hasta una hora de antigüedad.
Configura Pub/Sub para la autenticación push
En el siguiente ejemplo, se muestra cómo configurar la cuenta de servicio de autenticación de envío en
una cuenta de servicio de tu elección y cómo otorgar el
iam.serviceAccountTokenCreator
service-{PROJECT_NUMBER}@gcp-sa-pubsub.iam.gserviceaccount.com
agente de servicio.
Console
Ve a la página Suscripciones a Pub/Sub.
Haz clic en Crear suscripción.
Ingresa un nombre en el campo ID de la suscripción.
Selecciona un tema.
Selecciona Envío como el Tipo de entrega.
Ingresa una URL de extremo.
Marca Habilitar autenticación.
Selecciona una cuenta de servicio.
Asegúrate de que el agente de servicio
service-{PROJECT_NUMBER}@gcp-sa-pubsub.iam.gserviceaccount.com
tiene eliam.serviceAccountTokenCreator
rol en tu proyecto Panel de IAM. Si no se le otorgó el rol a la cuenta de servicio, haz clic en Otorgar en el panel de IAM para hacerlo.Opcional: Ingresa un público.
Haz clic en Crear.
gcloud
# Configure the push subscription gcloud pubsub subscriptions (create|update|modify-push-config) ${SUBSCRIPTION} \ --topic=${TOPIC} \ --push-endpoint=${PUSH_ENDPOINT_URI} \ --push-auth-service-account=${SERVICE_ACCOUNT_EMAIL} \ --push-auth-token-audience=${OPTIONAL_AUDIENCE_OVERRIDE} # Your service agent # `service-{PROJECT_NUMBER}@gcp-sa-pubsub.iam.gserviceaccount.com` needs to have the # `iam.serviceAccountTokenCreator` role. PUBSUB_SERVICE_ACCOUNT="service-${PROJECT_NUMBER}@gcp-sa-pubsub.iam.gserviceaccount.com" gcloud projects add-iam-policy-binding ${PROJECT_ID} \ --member="serviceAccount:${PUBSUB_SERVICE_ACCOUNT}"\ --role='roles/iam.serviceAccountTokenCreator'
Cuando habilites la autenticación para una suscripción push, es posible que veas un error permission denied
o not authorized
.
Para resolver este problema, asigna a la principal que inicia la creación o actualización de la suscripción el
iam.serviceAccounts.actAs
en la cuenta de servicio Para obtener más información,
consulta Autenticación en
“Crea suscripciones de envío”.
Si usas una suscripción de envío autenticada con un
aplicación de App Engine que está protegida con
Identity-Aware Proxy, debes proporcionar
ID de cliente de IAP como público del token de autenticación push.
Para habilitar IAP en tu aplicación de App Engine, consulta
Habilita IAP.
Para encontrar el ID de cliente de IAP, busca el ID de cliente IAP-App-Engine-app
en la
página Credenciales.
Reclamaciones
El JWT se puede usar para validar que los reclamos, incluidos los reclamos email
y aud
, estén firmados por Google. Consulta OpenID Connect si deseas obtener más información sobre cómo se pueden usar las API de OAuth 2.0 de Google para la autenticación y la autorización.
Hay dos mecanismos que hacen que estas afirmaciones tengan sentido. Primero,
Pub/Sub requiere que el usuario o la cuenta de servicio que realiza la
Llamadas CreateSubscription, UpdateSubscription o ModifyPushConfig para tener un rol
con el permiso iam.serviceAccounts.actAs
en el servicio de autenticación push
de servicio predeterminada. Un ejemplo de este tipo de rol es el rol roles/iam.serviceAccountUser
.
En segundo lugar, el acceso a los certificados usados para firmar los tokens está controlado de forma estricta. Para crear el token, Pub/Sub debe llamar a un
servicio de Google con una identidad de cuenta de servicio de firma independiente,
el agente de servicio
service-${PROJECT_NUMBER}@gcp-sa-pubsub.iam.gserviceaccount.com
Esta cuenta de servicio de firma debe tener la
permiso iam.serviceAccounts.getOpenIdToken
o un token de cuenta de servicio
Rol de creador (roles/iam.serviceAccountTokenCreator
) en la autenticación push
cuenta de servicio (o en cualquier recurso principal, como el proyecto, de la
cuenta de servicio de autenticación de envío).
Valida los tokens
Validar tokens enviados por Pub/Sub al extremo de envío involucra lo siguiente:
- Verificar la integridad del token mediante la validación de firmas
- Asegúrate de que las reclamaciones del correo electrónico y el público en el token coincidan con los valores establecidos en la configuración de suscripción de envío.
En el siguiente ejemplo, se muestra cómo autenticar una solicitud de inserción en una aplicación de App Engine que no está protegida con Identity-Aware Proxy. Si tu aplicación de App Engine
está asegurado con IAP, el encabezado de la solicitud HTTP que contiene las
JWT de IAP es x-goog-iap-jwt-assertion
y se debe validar según corresponda.
protocol
Solicitud:
GET https://oauth2.googleapis.com/tokeninfo?id_token={BEARER_TOKEN}
Respuesta:
200 OK
{ "alg": "RS256", "aud": "example.com", "azp": "104176025330667568672", "email": "{SERVICE_ACCOUNT_NAME}@{YOUR_PROJECT_NAME}.iam.gserviceaccount.com", "email_verified": "true", "exp": "1555463097", "iat": "1555459497", "iss": "https://accounts.google.com", "kid": "3782d3f0bc89008d9d2c01730f765cfb19d3b70e", "sub": "104176025330667568672", "typ": "JWT" }
C#
Antes de probar esta muestra, sigue las instrucciones de configuración de C# en la guía de inicio rápido sobre el uso de bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Pub/Sub para C#.
Go
Java
Node.js
Python
Ruby
Para obtener información sobre la variable de entorno PUBSUB_VERIFICATION_TOKEN
que se usó
en las muestras de código anteriores,
Consulta Escribe y responde mensajes de Pub/Sub.
Encuentra más ejemplos sobre cómo validar el JWT del portador en esta Guía para el Acceso con Google en sitios web Puedes encontrar una descripción general más amplia de los tokens de OpenID en la guía de OpenID Connect, incluida una lista de bibliotecas cliente que ayudan a validar JWT.
Autenticación de otros servicios de Google Cloud
Funciones de Cloud Run, App Engine y Cloud Run autentica las llamadas HTTP desde Pub/Sub verificando Tokens generados por Pub/Sub. La única configuración que necesitas es otorgar los roles de IAM necesarios a la cuenta del emisor.
Consulta los siguientes instructivos y guías para distintos casos de uso con estos servicios:
Cloud Run
- Activación desde la publicación de Pub/Sub: Tu cuenta de servicio de autenticación de publicación debe tener el rol
roles/run.invoker
y estar vinculada a un servicio de Cloud Run para invocar un servicio de Cloud Run correspondiente. - Instructivo de uso de Pub/Sub con Cloud Run
App Engine
Funciones de Cloud Run
- Activadores HTTP:
Tu cuenta de servicio de autenticación de envío debe tener la
roles/cloudfunctions.invoker
para invocar una función si quieres usar Pub/Sub solicitudes como activadores HTTP a la función - Activadores de Google Cloud Pub/Sub: Los roles y permisos de IAM se configuran automáticamente si usas Activadores de Pub/Sub para invocar una función