Uwierzytelniaj za pomocą logowania przez Facebooka na platformach Apple

Aby umożliwić użytkownikom uwierzytelnianie w Firebase za pomocą kont na Facebooku, możesz zintegrować z aplikacją Facebook Login lub Facebook Limited Login.

Zanim zaczniesz

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

  1. Po otwarciu projektu aplikacji przejdź w Xcode do File > Add Packages (Plik > 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 zależności w tle.

Następnie wykonaj kilka czynności konfiguracyjnych:

  1. Ze strony 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 metodę logowania Facebooka i podaj identyfikator aplikacji oraz tajny klucz aplikacji otrzymane z Facebooka.
    3. Następnie sprawdź, czy 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 stronie Facebook dla programistów w konfiguracji Ustawienia usługi > Logowanie przez Facebooka.

Zastosuj logowanie przez Facebooka

Aby użyć „klasycznego” logowania przez Facebooka, wykonaj poniższe czynności. Możesz też skorzystać z ograniczonego logowania przez Facebooka, jak pokazano w następnej sekcji.

  1. Zintegruj ze swoją aplikacją logowanie przez Facebooka, postępując zgodnie z dokumentacją dla deweloperów. Po zainicjowaniu obiektu FBSDKLoginButton ustaw przedstawiciela, który będzie otrzymywać zdarzenia logowania i 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 obiektu UIApplicationDelegate, a także wszystkie inne moduły Firebase używane przez przedstawiciela aplikacji. Aby na przykład użyć Cloud Firestore i Uwierzytelniania:

    Certyfikat 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 współdzieloną instancję FirebaseApp w metodzie application(_:didFinishLaunchingWithOptions:) przedstawiciela aplikacji:

    Certyfikat 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ć przedstawiciela aplikacji i dołączyć go do struktury App za pomocą UIApplicationDelegateAdaptor lub NSApplicationDelegateAdaptor. Musisz też wyłączyć przełączanie przekazywania dostępu do aplikacji. Więcej informacji znajdziesz w instrukcjach SwiftUI.

    Certyfikat 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 się zaloguje, w Twojej implementacji didCompleteWithResult:error: uzyskaj token dostępu dla zalogowanego użytkownika i wymień go danymi 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

Aby używać funkcji logowania ograniczonego przez Facebooka zamiast „klasycznego” logowania przez Facebooka, wykonaj poniższe czynności.

  1. Zintegruj ze swoją aplikacją logowanie ograniczone przez Facebooka, postępując zgodnie z dokumentacją dla deweloperów.
  2. Dla każdego żądania logowania wygeneruj unikalny losowy ciąg znaków (jednorazowy), którego będziesz używać do sprawdzania, czy otrzymany token tożsamości został przyznany w odpowiedzi na żądanie uwierzytelnienia aplikacji. Ten krok jest ważny, aby zapobiec 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 wyślesz identyfikator SHA-256 identyfikatora jednorazowego, który Facebook przekaże w odpowiedzi bez zmian. Firebase weryfikuje odpowiedź, szyfrując pierwotną liczbę jednorazową i porównując ją z wartością przekazaną 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. Po skonfigurowaniu FBSDKLoginButton ustaw przedstawiciela, który będzie otrzymywać zdarzenia logowania i wylogowania, ustaw tryb śledzenia na FBSDKLoginTrackingLimited i dołącz wartość 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 obiektu UIApplicationDelegate, a także wszystkie inne moduły Firebase używane przez przedstawiciela aplikacji. Aby na przykład użyć Cloud Firestore i Uwierzytelniania:

    Certyfikat 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 współdzieloną instancję FirebaseApp w metodzie application(_:didFinishLaunchingWithOptions:) przedstawiciela aplikacji:

    Certyfikat 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ć przedstawiciela aplikacji i dołączyć go do struktury App za pomocą UIApplicationDelegateAdaptor lub NSApplicationDelegateAdaptor. Musisz też wyłączyć przełączanie przekazywania dostępu do aplikacji. Więcej informacji znajdziesz w instrukcjach SwiftUI.

    Certyfikat 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ę, w Twojej implementacji didCompleteWithResult:error: użyj tokena identyfikatora z odpowiedzi Facebooka 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 loguje się po raz pierwszy, tworzone jest nowe konto użytkownika, które jest łączone z danymi logowania (nazwa użytkownika i hasło, numer telefonu lub informacje o dostawcy uwierzytelniania). Nowe konto jest przechowywane w ramach Twojego projektu Firebase i może być używane do identyfikowania użytkowników we wszystkich aplikacjach w Twoim projekcie niezależnie od tego, jak się on loguje.

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

  • W regułach zabezpieczeń Bazy danych czasu rzeczywistego Firebase i Cloud Storage możesz pobrać ze zmiennej auth unikalny identyfikator użytkownika zalogowanego użytkownika i użyć go do kontrolowania, do jakich danych użytkownik ma dostęp.

Możesz zezwolić użytkownikom na logowanie się w aplikacji przy użyciu różnych dostawców uwierzytelniania, łącząc dane logowania dostawcy uwierzytelniania z istniejącym kontem 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żesz też dodać kod obsługi błędów dla pełnego zakresu błędów uwierzytelniania. Patrz sekcja Obsługa błędów.