首页 > 解决方案 > Google Cloud Functions (GCF) works fine locally with Authentication header, but returns 401 when deployed

问题描述

I have function that has some code to check whether user is authenticated or not

export const addAffiliate = functions.region('us-central1').https.onCall(
  async (inputData: any, context: functions.https.CallableContext) => {
    checkAuthentication(context);
    ...
export const checkAuthentication = (
  context: functions.https.CallableContext
) => {
  // Checking that the user is authenticated.
  if (!context.auth) {
    // Throwing an HttpsError so that the client gets the error details.
    throw new functions.https.HttpsError(
      'failed-precondition',
      'The function must be called ' + 'while authenticated.'
    );
  }
};

To test it, I generate token using gcloud auth print-identity-token command, paste it into Authorization header with "Bearer " + token value and invoke it to get successful response. local test

However, when I deploy function, it does not even reach checkAuthentication method. It just instantly returns unauthenticated response (401). The workflow where I don't provide Authentication header works fine, I get 400 as expected. I can reproduce this behaviour locally only if I provide some garbage value into auth header.

{
    "error": {
        "message": "Unauthenticated",
        "status": "UNAUTHENTICATED"
    }
}

Function uses service account credentials for initialization. In deployed functions permissions its and mine accounts are listed. What could be a reason for deployed function not being able to read id token? enter image description here

标签: node.jsgoogle-cloud-functionsgcloud

解决方案


Can't find any reference, but looks like only firebase authentication works in both cases (locally and remote). In my case, I should not use google account id token, but a firebase user id token that has linked google account as external provider account.


推荐阅读