1
votes

I am using Firebase admin auth as authentication and authorization mechanism (client send token, server will validate and check users' roles contained in the custom claims) in my Cloud Run running graphql server. The admin auth module will throw error whenever it tries to call verifyIdToken. Calling admin auth methods from cloud functions work flawlessly though.

FirebaseAuthError: Must initialize app with a cert credential or set your Firebase project ID as the GOOGLE_CLOUD_PROJECT environment variable to call verifyIdToken().

I have tried using app engine service account (the same as the one used by cloud functions) and creating new one with firebase admin role as my cloud run's service account but resulted in no avail. I am able to make it run by providing the credentials file (generated from firebase console) in my Dockerfile and set the env variable GOOGLE_APPLICATION_CREDENTIALS, but I want to use that as the last resort beside it's very unsightly.

Below is my Apollo server's context function

import { Context, ContextFunction } from 'apollo-server-core';
import { ExpressContext } from 'apollo-server-express/dist/ApolloServer';

import { firebase } from '../config';
import { batchLoaders } from './batchLoaders';

export const context: ContextFunction<ExpressContext, Context> = async ({
  req
}) => {
  const token = req.headers.authorization || '';
  const defaultContext = { batchLoaders };

  if (token.length === 0) return defaultContext;

  try {
    const { uid } = await firebase.auth.verifyIdToken(token);
    const user = await firebase.auth.getUser(uid);
    return { uid, claims: user.customClaims, ...defaultContext };
  } catch (err) {
    console.error(err);
    return defaultContext;
  }
};

And the file in which it imports the firebase module from.

const firebaseApp = initializeApp();

const auth = firebaseApp.auth();

const firestore = firebaseApp.firestore();

export const firebase = {
  auth,
  firestore,
  refs: {
    events: firestore.collection('_events'),
    versions: firestore.collection('_versions')
  }
};

Isn't the same service account supposed to be able to access the admin auth resources?

2

2 Answers

5
votes

Dang my bad, The error message says it all, I need to provide GOOGLE_CLOUD_PROJECT in the cloud run env vars.

2
votes

adding GOOGLE_CLOUD_PROJECT as an environment variable on cloud run also solved my problementer image description here