Proteggi le risorse non Firebase con App Check nelle app Web

Puoi proteggere le risorse non Firebase della tua app, come i backend self-hosted, con App Check. Per fare ciò, dovrai eseguire entrambe le operazioni seguenti:

  • Modifica il client dell'app per inviare un token App Check insieme a ogni richiesta al backend, come descritto in questa pagina.
  • Modifica il tuo backend per richiedere un token App Check valido con ogni richiesta, come descritto in Verificare i token App Check da un backend personalizzato .

Prima di iniziare

Aggiungi App Check alla tua app, utilizzando il provider reCAPTCHA Enterprise o un provider personalizzato .

Invia token App Check con richieste di backend

Nel client dell'app, prima di ogni richiesta, ottieni un token App Check valido e non scaduto con appCheck().getToken() . Se necessario, la libreria App Check aggiornerà il token.

Una volta che hai un token valido, invialo insieme alla richiesta al tuo backend. Le specifiche su come eseguire questa operazione dipendono da te, ma non inviare token App Check come parte degli URL , inclusi i parametri di query, poiché ciò li rende vulnerabili a perdite e intercettazioni accidentali. L'esempio seguente invia il token in un'intestazione HTTP personalizzata, che è l'approccio consigliato.

Web modular API

import { initializeAppCheck, getToken } from 'firebase/app-check';

const appCheck = initializeAppCheck(
    app,
    { provider: provider } // ReCaptchaV3Provider or CustomProvider
);

const callApiWithAppCheckExample = async () => {
  let appCheckTokenResponse;
  try {
      appCheckTokenResponse = await getToken(appCheck, /* forceRefresh= */ false);
  } catch (err) {
      // Handle any errors if the token was not retrieved.
      return;
  }

  // Include the App Check token with requests to your server.
  const apiResponse = await fetch('https://yourbackend.example.com/yourApiEndpoint', {
      headers: {
          'X-Firebase-AppCheck': appCheckTokenResponse.token,
      }
  });

  // Handle response from your backend.
};

Web namespaced API

const callApiWithAppCheckExample = async () => {
  let appCheckTokenResponse;
  try {
      appCheckTokenResponse = await firebase.appCheck().getToken(/* forceRefresh= */ false);
  } catch (err) {
      // Handle any errors if the token was not retrieved.
      return;
  }

  // Include the App Check token with requests to your server.
  const apiResponse = await fetch('https://yourbackend.example.com/yourApiEndpoint', {
      headers: {
          'X-Firebase-AppCheck': appCheckTokenResponse.token,
      }
  });

  // Handle response from your backend.
};

Protezione dalla riproduzione (beta)

Quando effettui una richiesta a un endpoint per il quale hai abilitato la protezione dalla riproduzione , acquisisci un token utilizzando getLimitedUseToken() anziché getToken() :

import { getLimitedUseToken } from "firebase/app-check";

// ...

appCheckTokenResponse = await getLimitedUseToken(appCheck);