How to generate a Firebase ID Token
Firebase Functions has a https.onCall
trigger that supports calling the Function from your Firebase client.
For the Mobile and Web Firebase SDKs, authentication is handled for you. But if you want to call these Cloud Functions manually, you need a Firebase ID Token.
Generating an ID Token
Creating an ID Token is a two step process. We first create a Custom Token for a user, and then exchange that token for an ID Token.
Create a Custom Token
Using the firebase_admin
SDK, we can generate a Custom Token for a given Firebase Auth uid
(User ID).
from firebase_admin import initialize_app, auth
initialize_app()
uid = "T29cMsbYVyNTNQhnkIApXIBDWB73"
custom_token = auth.create_custom_token(uid)
This custom_token
doesn’t allow us to authenticate with Firestore. Instead, we must exchange this token for our ID Token using Google Cloud APIs.
Exchanging a Custom Token for ID Token
First, you’ll need a Google Cloud API Key which can be generated on the Google Cloud Console.
This API Key only needs Identity Toolkit access, so edit your key’s API restrictions to Identity Toolkit API
.
Now we can use our custom_token
from the previous step, along with our Google Cloud API key to call signInWithCustomToken
and retrieve an ID Token:
CUSTOM_TOKEN="custom_token-from-previous-step"
API_KEY="your-google-cloud-api-token"
curl -X POST \
"https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=$API_KEY" \
-H 'Content-Type: application/json' \
-d '{
{"token": "$CUSTOM_TOKEN", "returnSecureToken": true}
}'
{
"kind": "identitytoolkit#VerifyCustomTokenResponse",
"idToken": "<id.token.jwt>",
"refreshToken": "<refresh-token>",
"expiresIn": "3600",
"isNewUser": false
}
The idToken
in this response will allow us to authenticate with Firebase Functions.
Calling an Authenticated Firebase Function
With our idToken
, we can call our Firebase Function, using the protocol specification for https.onCall
as a reference.
ID_TOKEN="<id.token.jwt>"
curl -X POST \
'https://us-central1-firebase-project-name.cloudfunctions.net/myFunctionName' \
-H "Authentication: Bearer $ID_TOKEN" \
-H 'Content-Type: application/json' \
# firebase function arguments are passed in the `data` param:
-d '{
"data": {}
}'