Home > Net >  Do Callable Cloud Functions Ensure a Valid Token when Called
Do Callable Cloud Functions Ensure a Valid Token when Called

Time:06-24

I am calling a callable cloud function from a Javascript frontend and when calling Firebase in the past I would chain firebase.auth().currentUser.getIdToken(... before my call to the backend to ensure I had a valid token. Now that I am switching to callable cloud functions, I am wondering if this token refresh check is embedded in the callable itself or if I have to still check that my token is valid.

CodePudding user response:

When calling a method returned by the callable builder, like const myFunc = httpsCallable(funcName); myFunc(/* data */);, only the current ID token is attached. If the token has not yet expired, it is not forcibly refreshed.

At least for the JavaScript SDK, this is seen in the source code of packages/functions/src/service.ts and packages/functions/src/context.ts:

// in packages/functions/src/service.ts
const context = await functionsInstance.contextProvider.getContext();
if (context.authToken) {
  headers['Authorization'] = 'Bearer '   context.authToken;
}


// in packages/functions/src/context.ts
async getAuthToken(): Promise<string | undefined> {
  if (!this.auth) {
    return undefined;
  }

  try {
    const token = await this.auth.getToken();
    return token?.accessToken;
  } catch (e) {
    // If there's any error when trying to get the auth token, leave it off.
    return undefined;
  }
}

This essentially leads to the following decisions:

  • If Firebase Authentication isn't loaded, return undefined (don't attach any tokens).
  • If the no one is logged in, return null (don't attach any tokens).
  • If the token has expired, attempt to get a fresh one (and then attach it to the request).
  • If the token can't be obtained, return undefined (don't attach any tokens).
  • If the token has not expired, return the access token (and then attach it to the request).

Even though token expiry is handled by the SDK, you can still forcibly freshen up the token by using getIdToken(/* forciblyRefresh: */ true) before calling the function. The Cloud Functions SDK will call the Admin SDK to verify whatever token is sent as soon as the request is received regardless.

Aside from that, you can further enhance the security of your Cloud Function by enforcing a cutoff on how long ago the user signed into their account for privileged actions like account deletion, changing service account details and so on. This is done using the auth_time claim inside the access token's data or the authTime property on the id token object.

  • Related