Esegui l'autenticazione utilizzando GitHub sulle piattaforme Apple

Puoi consentire agli utenti di autenticarsi con Firebase utilizzando provider OAuth come GitHub integrando l'accesso OAuth generico nella tua app con l'SDK Firebase per eseguire il flusso di accesso end-to-end.

Prima di iniziare

Per consentire agli utenti di accedere utilizzando gli account GitHub, devi prima attivare GitHub come fornitore di accesso per il tuo progetto Firebase:

Utilizza Swift Package Manager per installare e gestire le dipendenze di Firebase.

  1. In Xcode, con il progetto dell'app aperto, vai a File > Aggiungi pacchetti.
  2. Quando richiesto, aggiungi il repository dell'SDK delle piattaforme Apple di Firebase:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. Scegli la raccolta Firebase Authentication.
  5. Aggiungi il flag -ObjC alla sezione Altri flag del linker delle impostazioni di compilazione del target.
  6. Al termine, Xcode inizierà automaticamente a risolvere e a scaricare le tue dipendenze in background.

Ora, svolgi alcuni passaggi di configurazione:

  1. Nella console Firebase, apri la sezione Auth.
  2. Nella scheda Metodo di accesso, attiva il provider GitHub.
  3. Aggiungi l'ID cliente e il client secret della console per sviluppatori del provider alla configurazione del provider:
    1. Registra la tua app come applicazione per sviluppatori su GitHub e ottieni l'ID client e il client secret OAuth 2.0 della tua app.
    2. Assicurati che l'URI di reindirizzamento OAuth di Firebase (ad es. my-app-12345.firebaseapp.com/__/auth/handler) sia impostato come URL di callback dell'autorizzazione nella pagina delle impostazioni dell'app nella configurazione dell'app GitHub.
  4. Fai clic su Salva.

Gestire il flusso di accesso con l'SDK Firebase

Per gestire il flusso di accesso con l'SDK Firebase per le piattaforme Apple:

  1. Aggiungi schema URL personalizzato al progetto Xcode:

    1. Apri la configurazione del progetto: fai doppio clic sul nome del progetto nella visualizzazione ad albero a sinistra. Seleziona la tua app dalla sezione TARGET, poi la scheda Informazioni ed espandi la sezione Tipi di URL.
    2. Fai clic sul pulsante + e aggiungi l'ID app codificato come schema URL. Puoi trovare l'ID app codificato nella pagina Impostazioni generali della Console Firebase, nella sezione relativa alla tua app per iOS. Lascia vuoti gli altri campi.

      Al termine, la configurazione dovrebbe avere un aspetto simile al seguente (ma con i valori specifici dell'applicazione):

      Screenshot dell'interfaccia di configurazione dello schema URL personalizzato di Xcode

  2. Crea un'istanza di OAuthProvider utilizzando l'ID provider github.com.

        var provider = OAuthProvider(providerID: "github.com")
        
        FIROAuthProvider *provider = [FIROAuthProvider providerWithProviderID:@"github.com"];
        
  3. Facoltativo: specifica ulteriori parametri OAuth personalizzati da inviare con la richiesta OAuth.

        provider.customParameters = [
          "allow_signup": "false"
        ]
        
        [provider setCustomParameters:@{@"allow_signup": @"false"}];
        

    Per i parametri supportati da GitHub, consulta la documentazione di GitHub OAuth. Tieni presente che non puoi passare i parametri richiesti da Firebase con setCustomParameters. Questi parametri sono client_id, redirect_uri, response_type, scope e state.

  4. Facoltativo: specifica gli ambiti OAuth 2.0 aggiuntivi oltre al profilo di base che vuoi richiedere al provider di autenticazione. Se la tua applicazione richiede l'accesso ai dati utente privati dalle API GitHub, dovrai richiedere le autorizzazioni per accedere alle API GitHub in Autorizzazioni API nella console per sviluppatori GitHub. Gli ambiti OAuth richiesti devono corrispondere esattamente a quelli preconfigurati nelle autorizzazioni API dell'app.

        // Request read access to a user's email addresses.
        // This must be preconfigured in the app's API permissions.
        provider.scopes = ["user:email"]
        
        // Request read access to a user's email addresses.
        // This must be preconfigured in the app's API permissions.
        [provider setScopes:@[@"user:email"]];
        

    Per saperne di più, consulta la documentazione sugli ambiti di GitHub.

  5. Facoltativo: se vuoi personalizzare il modo in cui la tua app presenta SFSafariViewController o UIWebView quando mostra reCAPTCHA all'utente, crea una classe personalizzata conforme al protocollo AuthUIDelegate e passala a credentialWithUIDelegate.

  6. Esegui l'autenticazione con Firebase utilizzando l'oggetto provider OAuth.

        provider.getCredentialWith(nil) { credential, error in
          if error != nil {
            // Handle error.
          }
          if credential != nil {
            Auth().signIn(with: credential) { authResult, error in
              if error != nil {
                // Handle error.
              }
              // User is signed in.
              // IdP data available in authResult.additionalUserInfo.profile.
    
              guard let oauthCredential = authResult.credential as? OAuthCredential else { return }
              // GitHub OAuth access token can also be retrieved by:
              // oauthCredential.accessToken
              // GitHub OAuth ID token can be retrieved by calling:
              // oauthCredential.idToken
            }
          }
        }
        
        [provider getCredentialWithUIDelegate:nil
                                   completion:^(FIRAuthCredential *_Nullable credential,
                                                NSError *_Nullable error) {
          if (error) {
           // Handle error.
          }
          if (credential) {
            [[FIRAuth auth] signInWithCredential:credential
                                      completion:^(FIRAuthDataResult *_Nullable authResult,
                                                NSError *_Nullable error) {
              if (error) {
                // Handle error.
              }
              // User is signed in.
              // IdP data available in authResult.additionalUserInfo.profile.
    
              FIROAuthCredential *oauthCredential = (FIROAuthCredential *)authResult.credential;
              // GitHub OAuth access token can also be retrieved by:
              // oauthCredential.accessToken
              // GitHub OAuth ID token can be retrieved by calling:
              // oauthCredential.idToken
            }];
          }
        }];
        

    Utilizzando il token di accesso OAuth, puoi chiamare l'API GitHub.

    Ad esempio, per ottenere informazioni di base sul profilo, puoi chiamare l'API REST, passando il token di accesso nell'intestazione Authorization:

    https://api.github.com/user
  7. Sebbene gli esempi precedenti si concentrino sui flussi di accesso, hai anche la possibilità di collegare un provider GitHub a un utente esistente. Ad esempio, puoi collegare più fornitori allo stesso utente, consentendogli di accedere con entrambi.

        Auth().currentUser.link(withCredential: credential) { authResult, error in
          if error != nil {
            // Handle error.
          }
          // GitHub credential is linked to the current user.
          // IdP data available in authResult.additionalUserInfo.profile.
          // GitHub OAuth access token can also be retrieved by:
          // (authResult.credential as? OAuthCredential)?.accessToken
          // GitHub OAuth ID token can be retrieved by calling:
          // (authResult.credential as? OAuthCredential)?.idToken
        }
        
        [[FIRAuth auth].currentUser
            linkWithCredential:credential
                    completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
          if (error) {
            // Handle error.
          }
          // GitHub credential is linked to the current user.
          // IdP data available in authResult.additionalUserInfo.profile.
          // GitHub OAuth access token is can also be retrieved by:
          // ((FIROAuthCredential *)authResult.credential).accessToken
          // GitHub OAuth ID token can be retrieved by calling:
          // ((FIROAuthCredential *)authResult.credential).idToken
        }];
        
  8. Lo stesso pattern può essere utilizzato con reauthenticateWithCredential, che può essere usato per recuperare credenziali aggiornate per operazioni sensibili che richiedono un accesso recente.

        Auth().currentUser.reauthenticateWithCredential(withCredential: credential) { authResult, error in
          if error != nil {
            // Handle error.
          }
          // User is re-authenticated with fresh tokens minted and
          // should be able to perform sensitive operations like account
          // deletion and email or password update.
          // IdP data available in result.additionalUserInfo.profile.
          // Additional OAuth access token is can also be retrieved by:
          // (authResult.credential as? OAuthCredential)?.accessToken
          // GitHub OAuth ID token can be retrieved by calling:
          // (authResult.credential as? OAuthCredential)?.idToken
        }
        
        [[FIRAuth auth].currentUser
            reauthenticateWithCredential:credential
                              completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
          if (error) {
            // Handle error.
          }
          // User is re-authenticated with fresh tokens minted and
          // should be able to perform sensitive operations like account
          // deletion and email or password update.
          // IdP data available in result.additionalUserInfo.profile.
          // Additional OAuth access token is can also be retrieved by:
          // ((FIROAuthCredential *)authResult.credential).accessToken
          // GitHub OAuth ID token can be retrieved by calling:
          // ((FIROAuthCredential *)authResult.credential).idToken
        }];
        

Se hai attivato l'impostazione Un account per indirizzo email nella console Firebase, quando un utente tenta di accedere a un provider (ad esempio GitHub) con un indirizzo email che esiste già per il provider di un altro utente Firebase (ad esempio Google), viene generato l'errore FIRAuthErrorCodeAccountExistsWithDifferentCredential insieme a un oggetto FIRAuthCredential temporaneo (credenziale GitHub). Per completare l'accesso al fornitore scelto, l'utente deve prima accedere al fornitore esistente (Google) e poi collegarsi al precedente FIRAuthCredential (credenziale GitHub). L'aspetto sarà come illustrato di seguito:

  // Sign-in with an OAuth credential.
  provider.getCredentialWith(nil) { credential, error in
    // An account with the same email already exists.
    if (error as NSError?)?.code == AuthErrorCode.accountExistsWithDifferentCredential.rawValue {
      // Get pending credential and email of existing account.
      let existingAcctEmail = (error! as NSError).userInfo[AuthErrorUserInfoEmailKey] as! String
      let pendingCred = (error! as NSError).userInfo[AuthErrorUserInfoUpdatedCredentialKey] as! AuthCredential
      // Lookup existing account identifier by the email.
      Auth.auth().fetchProviders(forEmail:existingAcctEmail) { providers, error in
        // Existing email/password account.
        if (providers?.contains(EmailAuthProviderID))! {
          // Existing password account for email. Ask user to provide the password of the
          // existing account.
          // Sign in with existing account.
          Auth.auth().signIn(withEmail:existingAcctEmail, password:password) { user, error in
            // Successfully signed in.
            if user != nil {
              // Link pending credential to account.
              Auth.auth().currentUser?.linkAndRetrieveData(with: pendingCred) { result, error in
                // ...
              }
            }
          }
        }
      }
      return
    }

    // Other errors.
    if error != nil {
      // handle the error.
      return
    }

    // Sign in with the credential.
    if credential != nil {
      Auth.auth().signInAndRetrieveData(with: credential!) { result, error in
        if error != nil {
          // handle the error.
          return
        }
      }
    }
  }

  
  // Sign-in with an OAuth credential.
  [provider getCredentialWithUIDelegate:nil
                             completion:^(FIRAuthCredential *_Nullable credential, NSError *_Nullable error) {
    // An account with the same email already exists.
    if (error.code == FIRAuthErrorCodeAccountExistsWithDifferentCredential) {
      // Get pending credential and email of existing account.
      NSString *existingAcctEmail = error.userInfo[FIRAuthErrorUserInfoEmailKey];
      FIRAuthCredential *pendingCred = error.userInfo[FIRAuthErrorUserInfoUpdatedCredentialKey];
      // Lookup existing account identifier by the email.
      [[FIRAuth auth] fetchProvidersForEmail:existingAcctEmail
                                 completion:^(NSArray<NSString *> *_Nullable providers,
                                              NSError *_Nullable error) {
        // Existing email/password account.
        if ( [providers containsObject:FIREmailAuthProviderID] ) {
          // Existing password account for email. Ask user to provide the password of the
          // existing account.

          // Sign in with existing account.
          [[FIRAuth auth] signInWithEmail:existingAcctEmail
                                 password:password
                               completion:^(FIRUser *user, NSError *error) {
            // Successfully signed in.
            if (user) {
              // Link pending credential to account.
              [[FIRAuth auth].currentUser linkWithCredential:pendingCred
                                                  completion:^(FIRUser *_Nullable user,
                                                               NSError *_Nullable error) {
                // ...
              }];
            }
          }];
        }
      }];
      return;
    }

    // Other errors.
    if (error) {
      // handle the error.
      return;
    }

    // Sign in with the credential.
    if (credential) {
      [[FIRAuth auth] signInAndRetrieveDataWithCredential:credential
          completion:^(FIRAuthDataResult *_Nullable authResult,
                       NSError *_Nullable error) {
        if (error) {
          // handle the error.
          return;
        }
      }];
    }
  }];
  

Passaggi successivi

Dopo che un utente ha eseguito l'accesso per la prima volta, viene creato un nuovo account utente e collegato alle credenziali, ovvero nome utente e password, numero di telefono o informazioni del fornitore di autenticazione, con cui l'utente ha eseguito l'accesso. Questo nuovo account viene archiviato nel tuo progetto Firebase e può essere utilizzato per identificare un utente in tutte le app del progetto, indipendentemente da come accede.

  • Nelle tue app, puoi recuperare le informazioni di base del profilo dell'utente dall'oggetto User . Vedi Gestire gli utenti.

  • Nelle Regole di sicurezza Firebase Realtime Database e Cloud Storage, puoi recuperare l'ID utente univoco dell'utente che ha eseguito l'accesso dalla variabile auth e utilizzarlo per controllare a quali dati può accedere un utente.

Puoi consentire agli utenti di accedere alla tua app utilizzando più provider di autenticazione collegando le credenziali del provider di autenticazione a un account utente esistente.

Per far uscire un utente, chiama signOut:.

let firebaseAuth = Auth.auth()
do {
  try firebaseAuth.signOut()
} catch let signOutError as NSError {
  print("Error signing out: %@", signOutError)
}
NSError *signOutError;
BOOL status = [[FIRAuth auth] signOut:&signOutError];
if (!status) {
  NSLog(@"Error signing out: %@", signOutError);
  return;
}

Ti consigliamo inoltre di aggiungere il codice di gestione degli errori per l'intera gamma di errori di autenticazione. Consulta la sezione Gestire gli errori.