Puoi proteggere le risorse non Firebase della tua app, come i backend self-hosted, con App Check. Per fare ciò, dovrai eseguire entrambe le seguenti operazioni:
- Modifica il client dell'app in modo che invii un token App Check insieme a ogni richiesta al tuo back-end, come descritto in questa pagina.
- Modifica il tuo back-end per richiedere un token App Check valido per ogni richiesta, come descritto in Verificare i token App Check da un back-end 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 back-end
Nel tuo client dell'app, prima di ogni richiesta, ottieni un token App Check valido e non scaduto con appCheck().getToken()
. La libreria App Check aggiornerà il token se necessario.
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, in quanto ciò li rende vulnerabili a fughe accidentali e intercettazioni. 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()
invece di getToken()
:
import { getLimitedUseToken } from "firebase/app-check";
// ...
appCheckTokenResponse = await getLimitedUseToken(appCheck);