Hello Team,
I hope you are doing well.
[details=Show More]
TL;DR: I want a JWT token with a long lifespan (e.g., 1 week or 1 month) to access a private Cloud Run service (https://
I am trying to access a Cloud Run Private Service i.e. https://-.cloudfunctions.net/, privately, from outside GCP with a JWT token
Now, when I generated a JWT token with this gcloud command:
gcloud auth print-identity-token
I accessed the Cloud Run service (example-name), but the token expires after approximately 1 hour.
I want to generate a token that lives longer than 1 hour (1 week/ 1 month,… etc) and give it to the consumer of the Cloud Run service; some services outside GCP don’t have access to it. So, it can only send API requests with bearer tokens.
I tried to create a custom JWT token but it has no access to the Cloud Run service (unauthorized user) . As follows:
import time
import jwt # Install with `pip install PyJWT`
import requests
SERVICE_ACCOUNT_KEY = "....."
# Service account details
SERVICE_ACCOUNT_EMAIL = SERVICE_ACCOUNT_KEY['client_email']
PRIVATE_KEY = SERVICE_ACCOUNT_KEY['private_key']
PRIVATE_KEY_ID = SERVICE_ACCOUNT_KEY['private_key_id']
CLOUD_FUNCTION_URL = "https://<region>-<project-id>.cloudfunctions.net/<EXAMPLE>"
# Create the JWT payload
iat = int(time.time())
exp = iat + 3600 # Token valid for 1 hour
payload = {
"iss": SERVICE_ACCOUNT_EMAIL,
"sub": SERVICE_ACCOUNT_EMAIL,
"aud": CLOUD_FUNCTION_URL,
"iat": iat,
"exp": exp,
}
# Create the JWT header
headers = {
"kid": PRIVATE_KEY_ID,
"alg": "RS256",
"typ": "JWT",
}
# Sign the JWT
signed_jwt = jwt.encode(payload, PRIVATE_KEY, algorithm="RS256", headers=headers)
The service key is frensh and valid, the service aaccount itself has these roles:
Cloud Functions Invoker
Cloud Run Invoker
Owner # for testing purposes
Service Account Token Creator
Example how I would access the cloud run service:
curl -X POST "https://<region>-<project-id>.cloudfunctions.net/<example-name>" -H "Authorization: Bearer {signed_jwt}" -H "Content-Type: application/json"'
Best regards,
Abdullah