Uwierzytelniaj za pomocą logowania przez Facebooka na platformach Apple

Możesz zezwolić użytkownikom na uwierzytelnianie w Firebase za pomocą ich kont na Facebooku integrując Facebook Login lub Facebook Limited Login ze swoją aplikacją.

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ę uwierzytelniania Firebase.
  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.

Następnie wykonaj kilka czynności konfiguracyjnych:

  1. na stronie Facebook for Developers, pobierz identyfikator aplikacji oraz tajny klucz aplikacji.
  2. Włącz logowanie przez Facebooka:
    1. W konsoli Firebase otwórz sekcję Uwierzytelnianie.
    2. Na karcie Metoda logowania włącz logowanie przez Facebooka oraz określ wartości App ID (Identyfikator aplikacji) i App Secret (Tajny klucz aplikacji) otrzymane od Facebooka.
    3. Następnie sprawdź, czy podany jest identyfikator URI przekierowania OAuth (np.my-app-12345.firebaseapp.com/__/auth/handler). jest wymieniony jako jeden z identyfikatorów URI przekierowania OAuth na stronie ustawień aplikacji Facebook na witrynie Facebook for Developers w Ustawienia produktu > Konfiguracja logowania do Facebooka.

Zastosuj logowanie przez Facebooka

Aby użyć słowa kluczowego „klasyczny” Zaloguj się do Facebooka, wykonaj następujące kroki. Ewentualnie możesz użyć funkcji logowania ograniczonego przez Facebooka, jak pokazano w następnej sekcji.

  1. Zintegruj logowanie przez Facebooka ze swoją aplikacją, postępując zgodnie z zapoznaj się z dokumentacją dla deweloperów. Po zainicjowaniu FBSDKLoginButton; ustaw przedstawiciela, aby otrzymywał logowanie i zdarzeń wylogowania. Przykład:

    Swift

    let loginButton = FBSDKLoginButton()
    loginButton.delegate = self
    

    Objective-C

    FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
    loginButton.delegate = self;
    
    Zaimplementuj didCompleteWithResult:error: przez przedstawiciela.

    Swift

    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
      if let error = error {
        print(error.localizedDescription)
        return
      }
      // ...
    }
    

    Objective-C

    - (void)loginButton:(FBSDKLoginButton *)loginButton
        didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
                        error:(NSError *)error {
      if (error == nil) {
        // ...
      } else {
        NSLog(error.localizedDescription);
      }
    }
    
  2. Zaimportuj moduł FirebaseCore do UIApplicationDelegate, jak i wszelkie inne Moduły Firebase używane przez przedstawiciela aplikacji. Aby na przykład użyć Cloud Firestore i Uwierzytelniania:

    SwiftUI

    import SwiftUI
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Swift

    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Objective-C

    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  3. Skonfiguruj FirebaseApp współdzielonej instancji w uprawnieniach przedstawiciela aplikacji Metoda application(_:didFinishLaunchingWithOptions:):

    SwiftUI

    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    Swift

    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
  4. Jeśli używasz SwiftUI, musisz utworzyć i dołączyć przedstawiciela aplikacji. do struktury App za pomocą UIApplicationDelegateAdaptor lub NSApplicationDelegateAdaptor Musisz też wyłączyć przełączanie przekazywania dostępu do aplikacji. Dla: więcej informacji znajdziesz w instrukcjach SwiftUI.

    SwiftUI

    @main
    struct YourApp: App {
      // register app delegate for Firebase setup
      @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    
      var body: some Scene {
        WindowGroup {
          NavigationView {
            ContentView()
          }
        }
      }
    }
          
  5. Gdy użytkownik zaloguje się poprawnie, w implementacji didCompleteWithResult:error:, uzyskaj token dostępu dla zalogowanym użytkownikiem i wymienić je na dane logowania Firebase:

    Swift

    let credential = FacebookAuthProvider
      .credential(withAccessToken: AccessToken.current!.tokenString)
    

    Objective-C

    FIRAuthCredential *credential = [FIRFacebookAuthProvider
        credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];
    

Wdrożenie funkcji logowania ograniczonego dostępu przez Facebooka

Używanie ograniczonego logowania przez Facebooka zamiast „klasycznego” Logowanie do Facebooka, ukończono te czynności.

  1. Zintegruj ze swoją aplikacją logowanie ograniczone przez Facebooka, postępując zgodnie z zapoznaj się z dokumentacją dla deweloperów.
  2. Dla każdego żądania logowania wygeneruj unikalny losowy ciąg znaków – będziesz używać do weryfikacji danych o tożsamości na żądanie uwierzytelnienia aplikacji. Ten krok jest ważny, i zapobiegania atakom typu „replay”. Możesz wygenerować kryptograficznie zabezpieczoną liczbę jednorazową za pomocą SecRandomCopyBytes(_:_:_) jak w tym przykładzie:

    Swift

    private func randomNonceString(length: Int = 32) -> String {
      precondition(length > 0)
      var randomBytes = [UInt8](repeating: 0, count: length)
      let errorCode = SecRandomCopyBytes(kSecRandomDefault, randomBytes.count, &randomBytes)
      if errorCode != errSecSuccess {
        fatalError(
          "Unable to generate nonce. SecRandomCopyBytes failed with OSStatus \(errorCode)"
        )
      }
    
      let charset: [Character] =
        Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._")
    
      let nonce = randomBytes.map { byte in
        // Pick a random character from the set, wrapping around if needed.
        charset[Int(byte) % charset.count]
      }
    
      return String(nonce)
    }
    
            

    Objective-C

    // Adapted from https://auth0.com/docs/api-auth/tutorials/nonce#generate-a-cryptographically-random-nonce
    - (NSString *)randomNonce:(NSInteger)length {
      NSAssert(length > 0, @"Expected nonce to have positive length");
      NSString *characterSet = @"0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._";
      NSMutableString *result = [NSMutableString string];
      NSInteger remainingLength = length;
    
      while (remainingLength > 0) {
        NSMutableArray *randoms = [NSMutableArray arrayWithCapacity:16];
        for (NSInteger i = 0; i < 16; i++) {
          uint8_t random = 0;
          int errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random);
          NSAssert(errorCode == errSecSuccess, @"Unable to generate nonce: OSStatus %i", errorCode);
    
          [randoms addObject:@(random)];
        }
    
        for (NSNumber *random in randoms) {
          if (remainingLength == 0) {
            break;
          }
    
          if (random.unsignedIntValue < characterSet.length) {
            unichar character = [characterSet characterAtIndex:random.unsignedIntValue];
            [result appendFormat:@"%C", character];
            remainingLength--;
          }
        }
      }
    
      return [result copy];
    }
            
    W żądaniu logowania wysyłasz hasz SHA-256 identyfikatora jednorazowego, który Facebook pozostanie bez zmian w odpowiedzi. Firebase weryfikuje odpowiedź przez zaszyfrowanie oryginalnej liczby jednorazowej i porównanie jej z przekazaną wartością przez Facebooka.

    Swift

    @available(iOS 13, *)
    private func sha256(_ input: String) -> String {
      let inputData = Data(input.utf8)
      let hashedData = SHA256.hash(data: inputData)
      let hashString = hashedData.compactMap {
        String(format: "%02x", $0)
      }.joined()
    
      return hashString
    }
    
            

    Objective-C

    - (NSString *)stringBySha256HashingString:(NSString *)input {
      const char *string = [input UTF8String];
      unsigned char result[CC_SHA256_DIGEST_LENGTH];
      CC_SHA256(string, (CC_LONG)strlen(string), result);
    
      NSMutableString *hashed = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
      for (NSInteger i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
        [hashed appendFormat:@"%02x", result[i]];
      }
      return hashed;
    }
            
  3. Podczas konfigurowania: FBSDKLoginButton ustaw przedstawiciela na odbierania zdarzeń logowania i wylogowania, należy ustawić tryb śledzenia na FBSDKLoginTrackingLimited i dołącz liczbę jednorazową. Przykład:

    Swift

    func setupLoginButton() {
        let nonce = randomNonceString()
        currentNonce = nonce
        loginButton.delegate = self
        loginButton.loginTracking = .limited
        loginButton.nonce = sha256(nonce)
    }
            

    Objective-C

    - (void)setupLoginButton {
      NSString *nonce = [self randomNonce:32];
      self.currentNonce = nonce;
      self.loginButton.delegate = self;
      self.loginButton.loginTracking = FBSDKLoginTrackingLimited
      self.loginButton.nonce = [self stringBySha256HashingString:nonce];
    }
            
    Zaimplementuj didCompleteWithResult:error: przez przedstawiciela.

    Swift

    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
      if let error = error {
        print(error.localizedDescription)
        return
      }
      // ...
    }
            

    Objective-C

    - (void)loginButton:(FBSDKLoginButton *)loginButton
        didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
                        error:(NSError *)error {
      if (error == nil) {
        // ...
      } else {
        NSLog(error.localizedDescription);
      }
    }
            
  4. Zaimportuj moduł FirebaseCore do UIApplicationDelegate, jak i wszelkie inne Moduły Firebase używane przez przedstawiciela aplikacji. Aby na przykład użyć Cloud Firestore i Uwierzytelniania:

    SwiftUI

    import SwiftUI
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Swift

    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Objective-C

    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  5. Skonfiguruj FirebaseApp współdzielonej instancji w uprawnieniach przedstawiciela aplikacji Metoda application(_:didFinishLaunchingWithOptions:):

    SwiftUI

    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    Swift

    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
  6. Jeśli używasz SwiftUI, musisz utworzyć i dołączyć przedstawiciela aplikacji. do struktury App za pomocą UIApplicationDelegateAdaptor lub NSApplicationDelegateAdaptor Musisz też wyłączyć przełączanie przekazywania dostępu do aplikacji. Dla: więcej informacji znajdziesz w instrukcjach SwiftUI.

    SwiftUI

    @main
    struct YourApp: App {
      // register app delegate for Firebase setup
      @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    
      var body: some Scene {
        WindowGroup {
          NavigationView {
            ContentView()
          }
        }
      }
    }
          
  7. Gdy użytkownik zaloguje się poprawnie, w implementacji didCompleteWithResult:error:, użyj tokena tożsamości z Facebooka odpowiedź z niezaszyfrowaną liczbą jednorazową, aby uzyskać dane logowania Firebase:

    Swift

    // Initialize a Firebase credential.
    let idTokenString = AuthenticationToken.current?.tokenString
    let nonce = currentNonce
    let credential = OAuthProvider.credential(withProviderID: "facebook.com",
                                              idToken: idTokenString!,
                                              rawNonce: nonce)
            

    Objective-C

    // Initialize a Firebase credential.
    NSString *idTokenString = FBSDKAuthenticationToken.currentAuthenticationToken.tokenString;
    NSString *rawNonce = self.currentNonce;
    FIROAuthCredential *credential = [FIROAuthProvider credentialWithProviderID:@"facebook.com"
                                                                        IDToken:idTokenString
                                                                       rawNonce:rawNonce];
            

Uwierzytelnij za pomocą Firebase

Na koniec uwierzytelnij w Firebase za pomocą danych logowania Firebase:

Swift

Auth.auth().signIn(with: credential) { authResult, error in
    if let error = error {
      let authError = error as NSError
      if isMFAEnabled, authError.code == AuthErrorCode.secondFactorRequired.rawValue {
        // The user is a multi-factor user. Second factor challenge is required.
        let resolver = authError
          .userInfo[AuthErrorUserInfoMultiFactorResolverKey] as! MultiFactorResolver
        var displayNameString = ""
        for tmpFactorInfo in resolver.hints {
          displayNameString += tmpFactorInfo.displayName ?? ""
          displayNameString += " "
        }
        self.showTextInputPrompt(
          withMessage: "Select factor to sign in\n\(displayNameString)",
          completionBlock: { userPressedOK, displayName in
            var selectedHint: PhoneMultiFactorInfo?
            for tmpFactorInfo in resolver.hints {
              if displayName == tmpFactorInfo.displayName {
                selectedHint = tmpFactorInfo as? PhoneMultiFactorInfo
              }
            }
            PhoneAuthProvider.provider()
              .verifyPhoneNumber(with: selectedHint!, uiDelegate: nil,
                                 multiFactorSession: resolver
                                   .session) { verificationID, error in
                if error != nil {
                  print(
                    "Multi factor start sign in failed. Error: \(error.debugDescription)"
                  )
                } else {
                  self.showTextInputPrompt(
                    withMessage: "Verification code for \(selectedHint?.displayName ?? "")",
                    completionBlock: { userPressedOK, verificationCode in
                      let credential: PhoneAuthCredential? = PhoneAuthProvider.provider()
                        .credential(withVerificationID: verificationID!,
                                    verificationCode: verificationCode!)
                      let assertion: MultiFactorAssertion? = PhoneMultiFactorGenerator
                        .assertion(with: credential!)
                      resolver.resolveSignIn(with: assertion!) { authResult, error in
                        if error != nil {
                          print(
                            "Multi factor finanlize sign in failed. Error: \(error.debugDescription)"
                          )
                        } else {
                          self.navigationController?.popViewController(animated: true)
                        }
                      }
                    }
                  )
                }
              }
          }
        )
      } else {
        self.showMessagePrompt(error.localizedDescription)
        return
      }
      // ...
      return
    }
    // User is signed in
    // ...
}
    

Objective-C

[[FIRAuth auth] signInWithCredential:credential
                          completion:^(FIRAuthDataResult * _Nullable authResult,
                                       NSError * _Nullable error) {
    if (isMFAEnabled && error && error.code == FIRAuthErrorCodeSecondFactorRequired) {
      FIRMultiFactorResolver *resolver = error.userInfo[FIRAuthErrorUserInfoMultiFactorResolverKey];
      NSMutableString *displayNameString = [NSMutableString string];
      for (FIRMultiFactorInfo *tmpFactorInfo in resolver.hints) {
        [displayNameString appendString:tmpFactorInfo.displayName];
        [displayNameString appendString:@" "];
      }
      [self showTextInputPromptWithMessage:[NSString stringWithFormat:@"Select factor to sign in\n%@", displayNameString]
                           completionBlock:^(BOOL userPressedOK, NSString *_Nullable displayName) {
       FIRPhoneMultiFactorInfo* selectedHint;
       for (FIRMultiFactorInfo *tmpFactorInfo in resolver.hints) {
         if ([displayName isEqualToString:tmpFactorInfo.displayName]) {
           selectedHint = (FIRPhoneMultiFactorInfo *)tmpFactorInfo;
         }
       }
       [FIRPhoneAuthProvider.provider
        verifyPhoneNumberWithMultiFactorInfo:selectedHint
        UIDelegate:nil
        multiFactorSession:resolver.session
        completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) {
          if (error) {
            [self showMessagePrompt:error.localizedDescription];
          } else {
            [self showTextInputPromptWithMessage:[NSString stringWithFormat:@"Verification code for %@", selectedHint.displayName]
                                 completionBlock:^(BOOL userPressedOK, NSString *_Nullable verificationCode) {
             FIRPhoneAuthCredential *credential =
                 [[FIRPhoneAuthProvider provider] credentialWithVerificationID:verificationID
                                                              verificationCode:verificationCode];
             FIRMultiFactorAssertion *assertion = [FIRPhoneMultiFactorGenerator assertionWithCredential:credential];
             [resolver resolveSignInWithAssertion:assertion completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
               if (error) {
                 [self showMessagePrompt:error.localizedDescription];
               } else {
                 NSLog(@"Multi factor finanlize sign in succeeded.");
               }
             }];
           }];
          }
        }];
     }];
    }
  else if (error) {
    // ...
    return;
  }
  // User successfully signed in. Get user data from the FIRUser object
  if (authResult == nil) { return; }
  FIRUser *user = authResult.user;
  // ...
}];
    

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 sposobu logowania się tego użytkownika.

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

  • W Bazie danych czasu rzeczywistego Firebase i Cloud Storage reguł zabezpieczeń, możesz 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:

Swift

let firebaseAuth = Auth.auth()
do {
  try firebaseAuth.signOut()
} catch let signOutError as NSError {
  print("Error signing out: %@", signOutError)
}

Objective-C

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 sekcja Obsługa błędów.