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 per inviare 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 con ogni richiesta, come descritto in Verifica dei token App Check da un back-end personalizzato .
Prima di iniziare
Aggiungi App Check alla tua app, utilizzando il provider reCAPTCHA v3 , il provider reCAPTCHA Enterprise o un provider personalizzato .
Invia token App Check con richieste di back-end
Nel 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 back-end. 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 version 9
const { initializeAppCheck, getToken } = require('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 version 8
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. };