Uwierzytelniaj za pomocą Twittera na platformach Apple

Możesz zezwolić użytkownikom na uwierzytelnianie w Firebase za pomocą dostawców protokołu OAuth, takich jak Twittera, integrując ogólne logowanie OAuth z aplikacją za pomocą pakietu SDK Firebase, i cały proces logowania.

Zanim zaczniesz

Użyj menedżera pakietów Swift, aby zainstalować zależności Firebase i nimi zarządzać.

  1. W Xcode po otwarciu projektu aplikacji przejdź do File > Dodaj pakiety.
  2. Gdy pojawi się prośba, dodaj repozytorium SDK platform Apple Platform SDK Firebase:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. Wybierz bibliotekę Firebase Authentication.
  5. Dodaj flagę -ObjC do sekcji Inne flagi łączące w ustawieniach kompilacji celu.
  6. Po zakończeniu Xcode automatycznie rozpocznie rozpoznawanie i pobieranie lub zależności w tle.

Aby logować użytkowników przy użyciu kont na Twitterze, musisz najpierw włączyć Twittera dla swojego projektu Firebase:

  1. Dodaj Firebase do projektu Apple.

  2. Uwzględnij w elemencie Podfile te pody:

    pod 'FirebaseAuth'
  3. W konsoli Firebase otwórz sekcję Uwierzytelnianie.
  4. Na karcie Metoda logowania włącz dostawcę Twittera.
  5. Dodaj klucz interfejsu API i tajny klucz interfejsu API z konsoli programisty tego dostawcy do konfiguracja dostawcy:
    1. Rejestrowanie aplikacji jako aplikację programistyczną na Twitterze i uzyskaj klucz interfejsu API swojej aplikacji OAuth. i Tajny klucz interfejsu API.
    2. Sprawdź, czy identyfikator URI przekierowania OAuth Firebase (np. my-app-12345.firebaseapp.com/__/auth/handler) jest ustawiony jako URL wywołania zwrotnego autoryzacji na stronie ustawień aplikacji Konfiguracja aplikacji Twittera.
  6. Kliknij Zapisz.

Zarejestruj się za pomocą pakietu SDK Firebase

Aby zalogować się za pomocą pakietu SDK platform Firebase Apple, wykonaj te czynności:

  1. Dodaj niestandardowe schematy adresów URL do projektu Xcode:

    1. Otwórz konfigurację projektu: kliknij dwukrotnie jego nazwę w lewy widok drzewa. Wybierz aplikację w sekcji CELE, a potem wybierz kartę Informacje i rozwiń sekcję Typy adresów URL.
    2. Kliknij przycisk + i dodaj zakodowany identyfikator aplikacji jako adres URL. oszustw. Zakodowany identyfikator aplikacji znajdziesz w Ogólne Ustawienia w konsoli Firebase w sekcji dotyczącej iOS. . Pozostałe pola pozostaw puste.

      Po zakończeniu konfiguracja powinna wyglądać podobnie do następujące (ale z wartościami związanymi z daną aplikacją):

      Zrzut ekranu interfejsu konfiguracji niestandardowego schematu adresu URL Xcode

  2. Utwórz instancję OAuthProvider za pomocą identyfikatora dostawcy. twitter.com

        var provider = OAuthProvider(providerID: "twitter.com")
        
        FIROAuthProvider *provider = [FIROAuthProvider providerWithProviderID:@"twitter.com"];
        
  3. Opcjonalnie: określ dodatkowe niestandardowe parametry OAuth, które chcesz stosować wysyłać z żądaniem OAuth.

        provider.customParameters = [
          "lang": "fr"
          ]
        
        [provider setCustomParameters:@{@"lang": @"fr"}];
        

    Parametry obsługiwane przez Twittera znajdziesz w Dokumentacja protokołu OAuth dla Twittera Pamiętaj, że parametrów wymaganych przez Firebase nie można przekazywać za pomocą funkcji setCustomParameters Te parametry to client_id, redirect_uri, response_type, scope i state.

  4. Opcjonalnie: jeśli chcesz dostosować sposób, w jaki aplikacja prezentuje SFSafariViewController lub UIWebView, gdy wyświetlając reCAPTCHA użytkownikowi, utwórz niestandardową klasę spełniającą wymagania do protokołu AuthUIDelegate i przekazać go do credentialWithUIDelegate.

  5. Uwierzytelniaj w Firebase za pomocą obiektu dostawcy OAuth.

        provider.getCredentialWith(nil) { credential, error in
          if error != nil {
            // Handle error.
          }
          if credential != nil {
            Auth.auth().signIn(with: credential) { authResult, error in
              if error != nil {
                // Handle error.
              }
              // User is signed in.
              // IdP data available in authResult.additionalUserInfo.profile.
              // Twitter OAuth access token can also be retrieved by:
              // (authResult.credential as? OAuthCredential)?.accessToken
              // Twitter OAuth ID token can be retrieved by calling:
              // (authResult.credential as? OAuthCredential)?.idToken
              // Twitter OAuth secret can be retrieved by calling:
              // (authResult.credential as? OAuthCredential)?.secret
            }
          }
        }
        
        [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.
              // Twitter OAuth access token can also be retrieved by:
              // authResult.credential.accessToken
              // Twitter OAuth ID token can be retrieved by calling:
              // authResult.credential.idToken
              // Twitter OAuth secret can be retrieved by calling:
              // authResult.credential.secret
            }];
          }
        }];
        

    Korzystając z tokena dostępu OAuth, możesz wywoływać metodę Interfejs Twitter API.

    Aby na przykład uzyskać podstawowe informacje o profilu, możesz wywołać interfejs API REST, przekazując token dostępu w nagłówku Authorization:

    https://api.twitter.com/labs/1/users?usernames=TwitterDev
  6. Powyższe przykłady dotyczą procesu logowania, ale masz też powiązanie dostawcy Twittera z istniejącym użytkownikiem. Możesz na przykład: Połączyć wielu dostawców z tym samym użytkownikiem, umożliwiając im logowanie się za pomocą dowolnej z tych usług.

        Auth().currentUser.link(withCredential: credential) { authResult, error in
          if error != nil {
            // Handle error.
          }
          // Twitter credential is linked to the current user.
          // IdP data available in authResult.additionalUserInfo.profile.
          // Twitter OAuth access token can also be retrieved by:
          // (authResult.credential as? OAuthCredential)?.accessToken
          // Twitter OAuth ID token can be retrieved by calling:
          // (authResult.credential as? OAuthCredential)?.idToken
          // Twitter OAuth secret can be retrieved by calling:
          // (authResult.credential as? OAuthCredential)?.secret
        }
        
        [[FIRAuth auth].currentUser
            linkWithCredential:credential
                    completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
          if (error) {
            // Handle error.
          }
          // Twitter credential is linked to the current user.
          // IdP data available in authResult.additionalUserInfo.profile.
          // Twitter OAuth access token is can also be retrieved by:
          // ((FIROAuthCredential *)authResult.credential).accessToken
          // Twitter OAuth ID token can be retrieved by calling:
          // ((FIROAuthCredential *)authResult.credential).idToken
          // Twitter OAuth secret can be retrieved by calling:
          // ((FIROAuthCredential *)authResult.credential).secret
        }];
        
  7. Tego samego wzorca można użyć z funkcją reauthenticateWithCredential, która może służy do pobierania nowych danych logowania na potrzeby operacji poufnych, które wymagają ostatniego logowania.

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

Jeśli w konsoli Firebase masz włączone ustawienie Jedno konto na każdy adres e-mail, gdy użytkownik próbuje zalogować się na konto usługi (takiej jak Twitter) przy użyciu adresu e-mail, dla dostawcy innego użytkownika Firebase (np. Google), błąd Rzucany FIRAuthErrorCodeAccountExistsWithDifferentCredential wraz z tymczasowym strzałem Obiekt FIRAuthCredential (dane logowania na Twitterze). Aby dokończyć logowanie się w do dostawcy usług, użytkownik musi najpierw zalogować się do istniejącego dostawcy (Google), a następnie dodać link poprzedni(a) FIRAuthCredential (dane logowania z Twittera). Wygląda to w taki sposób, jak pokazano poniżej:

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

Dalsze kroki

Gdy użytkownik zaloguje się po raz pierwszy, tworzone jest nowe konto użytkownika. powiązane z danymi logowania, czyli z nazwą użytkownika, hasłem i numerem telefonu, numer telefonu lub informacje o dostawcy uwierzytelniania – użytkownik zalogowany. Ten nowy jest przechowywane w ramach projektu Firebase i może służyć do identyfikowania użytkownika w każdej aplikacji w projekcie, niezależnie od tego, jak się loguje.

  • W swoich aplikacjach możesz uzyskać podstawowe informacje o profilu użytkownika z User . Zobacz Zarządzanie użytkownikami.

  • Na liście Firebase Realtime Database i Cloud Storage regułami zabezpieczeń, pobierz ze zmiennej auth unikalny identyfikator zalogowanego użytkownika, i używać ich do kontrolowania, do jakich danych użytkownik ma dostęp.

Możesz zezwolić użytkownikom na logowanie się w aplikacji przy użyciu wielokrotnego uwierzytelniania. dostawców, łącząc dane logowania dostawcy uwierzytelniania z istniejącego konta użytkownika.

Aby wylogować użytkownika, wywołaj 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;
}

Można także dodać kod obsługi błędów dla pełnego zakresu uwierzytelniania . Patrz Obsługa błędów.