How to create a Firebase token on the server for use with unit tests?

I need to authenticate a Firebase user with node so that I can test some methods on the server side. For each secure request, I check the Firebase token using:

firebase.auth().verifyIdToken(firebaseAccessToken).then(function(decodedToken) { // forward request }) 

So, in my test, I created a token with uid from the Firebase database

 firebase.auth().createCustomToken(uid).then(function(token) { //add to header for requests }) 

Later I read that user tokens are not verified by the verifyIdToken method, only generated by the client.

I looked at this answer - server side token check in firebase

So I added databaseAuthVariableOverride to init json

 firebase.initializeApp({ credential: firebase.credential.cert(serviceAccount), databaseURL: [dbURL], databaseAuthVariableOverride: { uid: [uid] } }); 

Still getting output in my tests

 Error: expected 200 "OK", got 401 "Unauthorized" 

And the firebase error is -

 Error: Decoding Firebase ID token failed. Make sure you passed the entire string JWT which represents an ID token. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token. 

So how do I emulate a user with my current setting?

+5
source share
2 answers

Here's a Python script for creating Firebase ID tokens (not custom tokens) .

 python firebase_token_generator.py <UID> 

There are probably simpler ways to do this, but you can invoke a Python script from Node.

0
source

You can generate a Firebase Id token from your custom token, and then use it for verification. For instance:

 const rp = require("request-promise"); // 'customToken' comes from FirebaseAdmin.auth().createCustomToken(uid) function getIdTokenFromCustomToken(customToken) { const url = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key=${API_KEY}'; const data = { token: customToken, returnSecureToken: true }; var options = { method: "POST", uri: url, body: data, json: true // Automatically stringifies the body to JSON }; return rp(options) // idToken is the firebase id token that can be used with verifyIdToken .then(parsedBody => parsedBody.idToken) .catch(function(err) { // POST failed... }); } 
0
source

Source: https://habr.com/ru/post/1263701/


All Articles