Article

Angular Firebase App Check

AOAnonymous One· Sep 1, 20221 min read
  • #Angular
  • #Firebase
  • #Firebase App Check

Angular Firebase App Check

Learn how to configure firebase app check in your angular application.

Filename: server.ts
...
// These polyfills are for firebase app-check Node.js
// @ts-ignore
globalThis.self = globalThis;
globalThis.fetch = require('node-fetch').default;
...
Filename: app.module.ts

import type { app } from 'firebase-admin';
import {initializeAppCheck, provideAppCheck, CustomProvider, ReCaptchaV3Provider} from "@angular/fire/app-check";
export const FIREBASE_ADMIN = new InjectionToken<app.App>('firebase-admin');

@NgModule({
  ...
  imports: [
    ...
    provideAppCheck((injector) =>  {
      const admin = injector.get<app.App|null>(FIREBASE_ADMIN, null);
      if (admin) {
        const provider = new CustomProvider({ getToken: () =>
            admin.
            appCheck().
            createToken(environment.firebase.appId, { ttlMillis: 604_800_000, /* 1 week */ }).
            then(({ token, ttlMillis: expireTimeMillis }) => ({ token, expireTimeMillis } ))
        });
        return initializeAppCheck(undefined, { provider, isTokenAutoRefreshEnabled: false });
      } else {
        const provider = new ReCaptchaV3Provider(environment.recaptcha3SiteKey);
        return initializeAppCheck(undefined, { provider, isTokenAutoRefreshEnabled: true });
      }
    }, [new Optional(), FIREBASE_ADMIN]),

    ...
  ],
  ...
})
export class AppModule { }
Filename: app.server.module.ts

import { NgModule } from '@angular/core';
import * as admin from 'firebase-admin';

import {AppModule, FIREBASE_ADMIN} from './app.module';

import {environment} from "../environments/environment";

@NgModule({
  ...
  providers: [
    { provide: FIREBASE_ADMIN, useFactory: () => admin.apps[0] || admin.initializeApp(
        // In Cloud Functions we can auto-initialize
        process.env.FUNCTION_NAME ? undefined : {
          credential: admin.credential.applicationDefault(),
          databaseURL: environment.firebase.databaseURL,
        }
      ) }
  ],
 ...
})
export class AppServerModule {}
Filename: environment.ts/environment.prod.ts

export const environment = {
 ...
  firebase: {
    ...
    databaseURL: 'https://<PROJECT-NAME>.firebaseio.com',
    ...
  },
  recaptcha3SiteKey: '<RECAPTCHA3-KEY-HERE>',
  ...
};

You will need to add your App Check debug token to the firebase console for your application to work in a local development environment.

If you get this error: 

 @firebase/app-check: FirebaseAppCheckError: Failed to determine service account. Make sure to initialize the SDK with a service acc
ount credential. Alternatively specify a service account with iam.serviceAccounts.signBlob permission. Original error: Error: Error while making request: getad
drinfo ENOTFOUND metadata. Error code: ENOTFOUND

 errorInfo: {
    code: 'app-check/invalid-credential',
    message: 'Failed to determine service account. Make sure to initialize the SDK with a service account credential. Alternatively specify a service account w
ith iam.serviceAccounts.signBlob permission. Original error: Error: Error while making request: getaddrinfo ENOTFOUND metadata. Error code: ENOTFOUND'
  },
  codePrefix: 'app-check'

And you are using Firebase AppCheck with admin.credential.applicationDefault() then you need to set the following environment variable: GOOGLEA_APPLICATION_CREDENTIALS like so:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"

After you've completed the above steps, Application Default Credentials (ADC) is able to implicitly determine your credentials, allowing you to use service account credentials when testing or running in non-Google environments.


References:

0 Comments

Sign in to join the conversation.

Search

Jump to a page, story or project