Eseguire l'autenticazione utilizzando Yahoo sulle piattaforme Apple

Puoi consentire ai tuoi utenti di eseguire l'autenticazione con Firebase utilizzando provider OAuth come Yahoo integrando l'accesso OAuth generico nell'app utilizzando l'SDK Firebase per di eseguire il flusso di accesso end-to-end.

Prima di iniziare

Per far accedere gli utenti utilizzando gli account Yahoo, devi prima abilitare Yahoo per le credenziali di accesso per il tuo progetto Firebase:

  1. Aggiungi Firebase al tuo progetto Apple.
  2. Nella console Firebase, apri la sezione Autorizzazione.
  3. Nella scheda Metodo di accesso, attiva il provider Yahoo.
  4. Aggiungi l'ID cliente e il client secret della console per sviluppatori del provider alla configurazione del provider:
    1. Per registrare un client Yahoo OAuth, segui lo sviluppatore Yahoo documentazione su di un'applicazione web con Yahoo.

      Assicurati di selezionare le due autorizzazioni dell'API OpenID Connect: profile e email.

    2. Quando registri app con questi fornitori, assicurati di registrare il dominio *.firebaseapp.com per il tuo progetto come dominio di reindirizzamento per dell'app.
  5. 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 schemi URL personalizzati al tuo progetto Xcode:

    1. Apri la configurazione del progetto: fai doppio clic sul nome del progetto nella vista 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 URL . Puoi trovare l'ID app codificato nella pagina Impostazioni generali della Console Firebase, nella sezione relativa all'app per iOS. Lascia vuoti gli altri campi.

      Una volta completata, la configurazione dovrebbe essere simile alla seguenti (ma con valori specifici per l'applicazione):

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

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

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

    provider.customParameters = [
    "prompt": "login",
    "language": "fr"
    ]
        
    [provider setCustomParameters:@{@"prompt": @"login", @"language": @"fr"}];
        

    Per i parametri supportati da Yahoo, consulta la documentazione di OAuth di Yahoo. 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 a profile e email che vuoi richiedere al provider di autenticazione. Se le tue richiede l'accesso a dati utente privati dalle API di Yahoo, dovrai devi richiedere le autorizzazioni alle API di Yahoo nella sezione Autorizzazioni API della Developer Console Yahoo. Gli ambiti OAuth richiesti devono corrispondere esattamente a quelli preconfigurati nelle autorizzazioni API dell'app. Ad esempio, se, in lettura/scrittura l'accesso è richiesto ai contatti degli utenti e preconfigurato nell'API dell'app autorizzazioni, è necessario trasmettere sdct-w anziché l'ambito OAuth di sola lettura sdct-r. In caso contrario, il flusso non andrà a buon fine e verrà mostrato un errore al prompt per l'utente finale.

    // Request access to Yahoo Mail API.
    // Request read/write access to user contacts.
    // This must be preconfigured in the app's API permissions.
    provider.scopes = ["mail-r", "sdct-w"]
        
    // Request access to Yahoo Mail API.
    // Request read/write access to user contacts.
    // This must be preconfigured in the app's API permissions.
    [provider setScopes:@[@"mail-r", @"sdct-w"]];
        

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

  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.
      // Yahoo OAuth access token can also be retrieved by:
      // (authResult.credential as? OAuthCredential)?.accessToken
      // Yahoo OAuth ID token can be retrieved by calling:
      // (authResult.credential as? 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.
      // Yahoo OAuth access token can also be retrieved by:
      // ((FIROAuthCredential *)authResult.credential).accessToken
      // Yahoo OAuth ID token can be retrieved by calling:
      // ((FIROAuthCredential *)authResult.credential).idToken
    }];
    }
    }];
        

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

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

    https://social.yahooapis.com/v1/user/YAHOO_USER_UID/profile?format=json

    Dove YAHOO_USER_UID è l'ID dell'utente Yahoo che è possibile recuperare da il campo Auth.auth.currentUser.providerData[0].uid o da authResult.additionalUserInfo.profile.

  7. Sebbene gli esempi precedenti si concentrino sui flussi di accesso, sono disponibili anche di collegare un provider Yahoo a un utente esistente utilizzando linkWithPopup. Ad esempio, puoi collegare più fornitori allo stesso utente consentendogli di accedere con uno dei due.

    Auth().currentUser.link(withCredential: credential) { authResult, error in
    if error != nil {
    // Handle error.
    }
    // Yahoo credential is linked to the current user.
    // IdP data available in authResult.additionalUserInfo.profile.
    // Yahoo OAuth access token can also be retrieved by:
    // (authResult.credential as? OAuthCredential)?.accessToken
    // Yahoo 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.
    }
    // Yahoo credential is linked to the current user.
    // IdP data available in authResult.additionalUserInfo.profile.
    // Yahoo OAuth access token is can also be retrieved by:
    // ((FIROAuthCredential *)authResult.credential).accessToken
    // Yahoo OAuth ID token can be retrieved by calling:
    // ((FIROAuthCredential *)authResult.credential).idToken
    }];
        
  8. Lo stesso pattern può essere utilizzato con reauthenticateWithPopup/reauthenticateWithRedirect, che può essere utilizzato per recuperare le 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
    // Yahoo 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
    // Yahoo 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 (come Yahoo) con un indirizzo email che esiste per un altro provider utente Firebase (come Google), l'errore FIRAuthErrorCodeAccountExistsWithDifferentCredential viene lanciato insieme a un evento Oggetto FIRAuthCredential (credenziale Yahoo). Per completare l'accesso al il fornitore previsto, l'utente deve prima accedere al fornitore esistente (Google) e poi collegarsi al precedente FIRAuthCredential (credenziale Yahoo). L'URL avrà il seguente aspetto:

  // 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;
        }
      }];
    }
  }];
  

A differenza di altri provider OAuth supportati da Firebase, come Google, Facebook, e Twitter, dove è possibile accedere direttamente con il token di accesso OAuth basate su credenziali, Firebase Auth non supporta la stessa funzionalità come Yahoo a causa dell'incapacità di Firebase Server di autenticazione per verificare il pubblico dei token di accesso di Yahoo OAuth. Si tratta di un requisito di sicurezza fondamentale e potrebbe esporre applicazioni e siti web ad attacchi di replay in cui un token di accesso OAuth di Yahoo ottenuto per un progetto (aggressore) può essere utilizzato per accedere a un altro progetto (vittima). Firebase Auth offre invece la possibilità di gestire l'intero flusso OAuth lo scambio del codice di autorizzazione utilizzando l'ID client e il secret OAuth configurate nella console Firebase. Poiché il codice di autorizzazione può essere utilizzato solo in combinazione con un ID client/una secret specifici, un codice di autorizzazione ottenuto per un progetto non può essere utilizzato con un altro.

Se è necessario utilizzare questi provider in ambienti non supportati, libreria OAuth di terze parti Autenticazione personalizzata Firebase deve essere usato. Il primo è necessario per l'autenticazione con il fornitore e il secondo per scambiare la credenziale del fornitore con un token personalizzato.

Passaggi successivi

Dopo che un utente ha eseguito l'accesso per la prima volta, viene creato un nuovo account utente e collegati alle credenziali, ovvero nome utente, password, numero o informazioni del provider di autenticazione, ovvero l'utente con cui 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ù autenticazioni collegando le credenziali del provider di autenticazione a un a un account utente esistente.

Per disconnettere 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;
}

Potresti anche voler aggiungere il codice per la gestione degli errori per l'intero intervallo di autenticazione errori. Consulta la sezione Gestire gli errori.

Firebase Authentication lets you add an end-to-end identity solution to your app for easy user authentication, sign-in, and onboarding in just a few lines of code.

Aggiornamento: Feb 28, 2025

Firebase Authentication lets you add an end-to-end identity solution to your app for easy user authentication, sign-in, and onboarding in just a few lines of code.

Aggiornamento: Feb 28, 2025

Firebase Authentication lets you add an end-to-end identity solution to your app for easy user authentication, sign-in, and onboarding in just a few lines of code.

Aggiornamento: Feb 28, 2025