My firebase cloud function contains protected routes that can only be accessed when passed a valid IdToken in the request header. cloud functions API looks like this
functions/index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: "DB_URL"
});
const express = require('express');
const app = express();
const authenticate = async (req, res, next) => {
if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) {
res.status(403).send('Unauthorized');
return;
}
const idToken = req.headers.authorization.split('Bearer ')[1];
try {
const decodedIdToken = await admin.auth().verifyIdToken(idToken);
req.user = decodedIdToken;
next();
return;
} catch(e) {
res.status(403).send('Unauthorized');
return;
}
};
app.use(authenticate);
app.get('/protected', async (req, res) => {
return res.send('OK');
});
exports.api = functions.https.onRequest(app);
Initially, I was using the Firebase Authentication to create new user and to get IdToken
curl 'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API_KEY]' \
-H 'Content-Type: application/json' \
--data-binary '{"email":"[user@example.com]","password":"[PASSWORD]","returnSecureToken":true}'
Getting IdToken so I can pass it to the firebase cloud functions to access the protected routes
curl 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=[API_KEY]' \
-H 'Content-Type: application/json' \
--data-binary '{"email":"[user@example.com]","password":"[PASSWORD]","returnSecureToken":true}'
calling my protected cloud functions using this approach is working fine
curl --location --request GET 'http://localhost:5001/abc-production/us-central1/api/protected/' \
--header 'Authorization: Bearer SECRET_ID_TOKEN'
Now, Instead of using the Firebase Authentication, I'd like to use the Authentication Emulator to create new users and generate IdToken's.
I can create new users using the Auth emulator UI, but how do I generate the access token of those users? Are there any API endpoints that can return the IdToken of the locally saved user so that I can test my protected API without adding users in production?
Also, When I run the auth emulator, IdToken's generated using the production Firebase Authentication environment doesn't work.
"code": "auth/argument-error",
"message": "Firebase ID token has invalid signature. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token."