Accesso degli utenti con GitHub

Questo documento mostra come utilizzare Identity Platform per accedere agli utenti con GitHub.

Prima di iniziare

Questo tutorial presuppone che tu abbia già attivato Identity Platform e abbia un'app web di base scritta utilizzando HTML e JavaScript. Per scoprire come fare, consulta la Guida rapida.

Configurazione di GitHub come provider

Per configurare GitHub come provider di identità:

  1. Vai alla pagina Provider di identità nella console Google Cloud.

    Vai alla pagina Provider di identità

  2. Fai clic su Add A Provider (Aggiungi un provider).

  3. Seleziona GitHub dall'elenco.

  4. Inserisci il tuo ID client e il client secret GitHub. Se non disponi già di un ID e di un secret, puoi ottenerne uno nella pagina Applicazioni GitHub.

  5. Configura l'URI elencato in Configura GitHub come URI di reindirizzamento OAuth valido per la tua app GitHub. Se hai configurato un dominio personalizzato in Identity Platform, aggiorna l'URI di reindirizzamento nella configurazione dell'app GitHub in modo da utilizzare il dominio personalizzato anziché il dominio predefinito. Ad esempio, cambia https://myproject.firebaseapp.com/__/auth/handler in https://auth.myownpersonaldomain.com/__/auth/handler.

  6. Registra i domini della tua app facendo clic su Aggiungi dominio in Domini autorizzati. A scopo di sviluppo, localhost è già abilitato per impostazione predefinita.

  7. In Configura la tua applicazione, fai clic su Dettagli di configurazione. Copia lo snippet nel codice della tua app per inizializzare l'SDK client di Identity Platform.

  8. Fai clic su Salva.

Accesso degli utenti con l'SDK client

  1. Crea un'istanza dell'oggetto del provider GitHub:

    Versione web 9

    import { GithubAuthProvider } from "firebase/auth";
    
    const provider = new GithubAuthProvider();

    Versione web 8

    var provider = new firebase.auth.GithubAuthProvider();
  1. Facoltativo:aggiungi ambiti OAuth. Gli ambiti specificano quali dati hai richiesto a GitHub. Dati più sensibili potrebbero richiedere ambiti specifici. Consulta la documentazione del provider per determinare gli ambiti necessari all'applicazione.

    Versione web 9

    provider.addScope('repo');

    Versione web 8

    provider.addScope('repo');
  1. (Facoltativo) Localizza il flusso di autenticazione. Puoi specificare una lingua o utilizzare la lingua predefinita del dispositivo:

    Versione web 9

    import { getAuth } from "firebase/auth";
    
    const auth = getAuth();
    auth.languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // auth.useDeviceLanguage();

    Versione web 8

    firebase.auth().languageCode = 'it';
    // To apply the default browser preference instead of explicitly setting it.
    // firebase.auth().useDeviceLanguage();
  2. (Facoltativo) Specifica altri parametri OAuth personalizzati. Questi strumenti sono specifici di GitHub e in genere vengono utilizzati per personalizzare l'esperienza di autenticazione. Non puoi trasmettere parametri riservati a OAuth o Identity Platform.

Versione web 9

provider.setCustomParameters({
  'allow_signup': 'false'
});

Versione web 8

provider.setCustomParameters({
  'allow_signup': 'false'
});
  1. Utilizza l'oggetto provider GitHub per accedere all'utente. Puoi aprire una finestra popup o reindirizzare la pagina corrente. Il reindirizzamento è più semplice per gli utenti che usano dispositivi mobili.

    Per visualizzare un popup, chiama signInWithPopup():

    Versione web 9

    import { getAuth, signInWithPopup, GithubAuthProvider } from "firebase/auth";
    
    const auth = getAuth();
    signInWithPopup(auth, provider)
      .then((result) => {
        // This gives you a GitHub Access Token. You can use it to access the GitHub API.
        const credential = GithubAuthProvider.credentialFromResult(result);
        const token = credential.accessToken;
    
        // The signed-in user info.
        const user = result.user;
        // IdP data available using getAdditionalUserInfo(result)
        // ...
      }).catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.customData.email;
        // The AuthCredential type that was used.
        const credential = GithubAuthProvider.credentialFromError(error);
        // ...
      });

    Versione web 8

    firebase
      .auth()
      .signInWithPopup(provider)
      .then((result) => {
        /** @type {firebase.auth.OAuthCredential} */
        var credential = result.credential;
    
        // This gives you a GitHub Access Token. You can use it to access the GitHub API.
        var token = credential.accessToken;
    
        // The signed-in user info.
        var user = result.user;
        // IdP data available in result.additionalUserInfo.profile.
          // ...
      }).catch((error) => {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // The email of the user's account used.
        var email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        var credential = error.credential;
        // ...
      });

    Per reindirizzare la pagina, chiama prima signInWithRedirect().

    Segui le best practice quando utilizzi signInWithRedirect, linkWithRedirect o reauthenticateWithRedirect.

    Versione web 9

    import { getAuth, signInWithRedirect } from "firebase/auth";
    
    const auth = getAuth();
    signInWithRedirect(auth, provider);

    Versione web 8

    firebase.auth().signInWithRedirect(provider);

    Quindi, recupera il token GitHub chiamando getRedirectResult() durante il caricamento della pagina:

    Versione web 9

    import { getAuth, getRedirectResult, GithubAuthProvider } from "firebase/auth";
    
    const auth = getAuth();
    getRedirectResult(auth)
      .then((result) => {
        const credential = GithubAuthProvider.credentialFromResult(result);
        if (credential) {
          // This gives you a GitHub Access Token. You can use it to access the GitHub API.
          const token = credential.accessToken;
          // ...
        }
    
        // The signed-in user info.
        const user = result.user;
        // IdP data available using getAdditionalUserInfo(result)
        // ...
      }).catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.customData.email;
        // The AuthCredential type that was used.
        const credential = GithubAuthProvider.credentialFromError(error);
        // ...
      });

    Versione web 8

    firebase.auth()
      .getRedirectResult()
      .then((result) => {
        if (result.credential) {
          /** @type {firebase.auth.OAuthCredential} */
          var credential = result.credential;
    
          // This gives you a GitHub Access Token. You can use it to access the GitHub API.
          var token = credential.accessToken;
          // ...
        }
    
        // The signed-in user info.
        var user = result.user;
        // IdP data available in result.additionalUserInfo.profile.
          // ...
      }).catch((error) => {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // The email of the user's account used.
        var email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        var credential = error.credential;
        // ...
      });

Una volta ottenuto un token di accesso, puoi utilizzarlo per chiamare l'API GitHub. Ad esempio:

REST

curl -H "Authorization: Bearer [TOKEN]" https://api.github.com/gists/starred

Accesso manuale agli utenti

Se non desideri utilizzare l'SDK client, puoi anche gestire il flusso di accesso manualmente:

  1. Integra l'autenticazione GitHub nella tua app seguendo i passaggi nella documentazione per gli sviluppatori.

  2. Accedi all'utente con GitHub utilizzando il flusso implementato nel passaggio precedente.

  3. Scambia il token che ricevi da GitHub con una credenziale di Identity Platform:

    Versione web 9

    import { GithubAuthProvider } from "firebase/auth";
    
    const credential = GithubAuthProvider.credential(token);

    Versione web 8

    var credential = firebase.auth.GithubAuthProvider.credential(token);
  4. Utilizza la credenziale per accedere all'utente con Identity Platform:

    Versione web 9

    import { getAuth, signInWithCredential } from "firebase/auth";
    
    // Sign in with the credential from the user.
    const auth = getAuth();
    signInWithCredential(auth, credential)
      .then((result) => {
        // Signed in
        // ...
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.customData.email;
        // ...
      });

    Versione web 8

    // Sign in with the credential from the user.
    firebase.auth()
      .signInWithCredential(credential)
      .then((result) => {
        // Signed in
        // ...
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.email;
        // ...
      });

Passaggi successivi