Puoi utilizzare App Check per proteggere le risorse di backend personalizzate non Google per la tua app, ad esempio il tuo backend self-hosted. A questo scopo, dovrai eseguire entrambe le seguenti operazioni:
- Modificare il client dell'app per inviare un token App Check insieme a ogni richiesta al backend, come descritto in questa pagina.
- Modificare il backend in modo che richieda 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.
Inviare token App Check con le richieste di backend
Nel client dell'app, prima di ogni richiesta, recupera un token valido e non scaduto con App Check
token con appCheck().getToken(). Se necessario, la libreria App Check aggiornerà il
token.
Una volta ottenuto un token valido, invialo insieme alla richiesta al backend. Le specifiche su come eseguire questa operazione dipendono da te, ma non inviare App Check token come parte degli URL, inclusi i parametri di query, in quanto 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
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
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 di riproduzione (beta)
Quando effettui una richiesta a un endpoint per il quale hai attivato la
protezione di riproduzione,
acquisisci un token utilizzando getLimitedUseToken() anziché getToken():
import { getLimitedUseToken } from "firebase/app-check";
// ...
appCheckTokenResponse = await getLimitedUseToken(appCheck);