dennying
dennying

Reputation: 35

firebase-admin auth error while calling `getUser`, but work fine when calling verifyToken

While using firebase-admin on server-side, I need to get user data from the firebase authentication. But I found that if I use jwt token which firebase provided, I couldn't get email or other providers' data from decoding token. (pretty sure that I've added specific scopes properly.)

Then I turned to using firebase admin api to get user data from firebase's authentication.

The code look like this:

import * as admin from 'firebase-admin'

const auth = admin.auth()
auth.verifyIdToken(idToken)
  .then(decodedToken => decodedToken.user_id)
  .then(uid => {
    auth.getUser(user_id)
      .then((userRecord) => {
        console.log("Successfully fetched user data:", userRecord.json());
      })
      .catch(function(error) {
        console.log("Error fetching user data:", error);
      });
  })

Then I got an error:

Error fetching user data: Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
   at Error (native)
   at Sign.sign (crypto.js:283:26)
   at Object.sign (~/app/node_modules/jwa/index.js:55:45)
   at Object.jwsSign [as sign] (~/app/node_modules/jws/lib/sign-stream.js:23:24)
   at Object.module.exports [as sign] (~/app/node_modules/firebase-admin/node_modules/jsonwebtoken/sign.js:144:16)
   at CertCredential.createAuthJwt_ (~/app/node_modules/firebase-admin/lib/auth/credential.js:190:20)
   at CertCredential.getAccessToken (~/app/node_modules/firebase-admin/lib/auth/credential.js:162:26)
   at SignedApiRequestHandler.sendRequest (~/app/node_modules/firebase-admin/lib/utils/api-request.js:110:32)
   at ~/app/node_modules/firebase-admin/lib/auth/auth-api-request.js:381:50
   at process._tickDomainCallback (internal/process/next_tick.js:129:7)

This might be a permission error, according to this guess, I've found this might be related to this problem on stackoverflow:

Firebase admin().auth().getUser(uid) Error: An internal error has occurred 'auth/internal-error'

But even I change the IAM of admin client to role: editor, this error still happened. Wondering what's going on, and why admin can verify token but can be granted to read user data (even I give the service account root access to my project).

Any suggestion would be helpful for me.

Upvotes: 3

Views: 1661

Answers (1)

jwngr
jwngr

Reputation: 4422

My best bet as to what is going wrong is that the private key within the service account key file you are using is invalid. To get a valid service account key file, follow the instructions in Add Firebase to your app. There is a nice UI which you can use to generate a new JSON file which should have all the proper permissions for your project. You can use it to initialize your SDK like this:

var serviceAccount = require("path/to/serviceAccountKey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

Upvotes: 2

Related Questions