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