Uwierzytelniaj za pomocą logowania przez Facebooka na platformach Apple

Możesz umożliwić użytkownikom uwierzytelnianie się w Firebase za pomocą kont Facebooka, integrując w swojej aplikacji logowanie Facebook lub logowanie Facebooka z ograniczonym dostępem.

Zanim zaczniesz

Do instalacji zależności Firebase i zarządzania nimi możesz używać menedżera pakietów Swift.

  1. Po otwarciu projektu aplikacji w Xcode wybierz Plik > Dodaj pakiety.
  2. Gdy pojawi się prośba, dodaj repozytorium pakietu SDK Firebase na platformy Apple:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. Wybierz bibliotekę Firebase Authentication.
  5. Dodaj flagę -ObjC do sekcji Inne flagi linkera w ustawieniach kompilacji docelowej.
  6. Gdy to zrobisz, Xcode automatycznie zacznie wyszukiwać i pobierać zależności w tle.

Następnie wykonaj czynności konfiguracyjne:

  1. Na stronie Facebook for Developers pobierz identyfikator aplikacji i klucz tajny aplikacji.
  2. Włącz logowanie przez Facebooka:
    1. W konsoli Firebase otwórz sekcję Uwierzytelnianie.
    2. Na karcie Metoda logowania włącz metodę logowania Facebook i wskaż identyfikator aplikacji oraz klucz tajny aplikacji otrzymane od Facebooka.
    3. Następnie sprawdź, czy identyfikator URI przekierowania OAuth (np. my-app-12345.firebaseapp.com/__/auth/handler) jest podany jako jeden z identyfikatorów URI przekierowania OAuth na stronie ustawień aplikacji na Facebooku na stronie Facebook for Developers w sekcji Ustawienia usługi > Logowanie na Facebooku.

Implementowanie logowania przez Facebooka

Aby korzystać z „klasycznego” logowania na Facebooku, wykonaj te czynności. Możesz też użyć opcji logowania na Facebooku z ograniczonymi uprawnieniami, jak opisano w następnej sekcji.

  1. Zintegruj logowanie na Facebooku ze swoją aplikacją, postępując zgodnie z  dokumentacją dla deweloperów. Podczas inicjowania obiektu FBSDKLoginButton ustaw delegata, który będzie odbierał zdarzenia logowania i wylogowywania. Przykład:
    let loginButton = FBSDKLoginButton()
    loginButton.delegate = self
    FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
    loginButton.delegate = self;
    W ramach delegowania implementuj didCompleteWithResult:error:.
    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
      if let error = error {
        print(error.localizedDescription)
        return
      }
      // ...
    }
    - (void)loginButton:(FBSDKLoginButton *)loginButton
        didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
                        error:(NSError *)error {
      if (error == nil) {
        // ...
      } else {
        NSLog(error.localizedDescription);
      }
    }
  2. Zaimportuj moduł FirebaseCore w pliku UIApplicationDelegate, a także wszystkie inne moduły Firebase, których używa delegowany obiekt aplikacji. Aby na przykład użyć właściwości Cloud FirestoreAuthentication:
    import SwiftUI
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          
    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  3. Skonfiguruj współdzieloną instancję FirebaseApp w metodzie application(_:didFinishLaunchingWithOptions:) w delegacie aplikacji:
    // Use Firebase library to configure APIs
    FirebaseApp.configure()
    // Use Firebase library to configure APIs
    FirebaseApp.configure()
    // Use Firebase library to configure APIs
    [FIRApp configure];
  4. Jeśli używasz SwiftUI, musisz utworzyć obiekt delegujący aplikacji i dołączyć go do struktury App za pomocą funkcji UIApplicationDelegateAdaptor lub NSApplicationDelegateAdaptor. Musisz też wyłączyć swizlowanie zastępników aplikacji. Więcej informacji znajdziesz w instrukcjach dotyczących 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. Po zalogowaniu się użytkownika w ramach implementacji interfejsu didCompleteWithResult:error: pobierz token dostępu dla zalogowanego użytkownika i wymień go na dane logowania Firebase:
    let credential = FacebookAuthProvider
      .credential(withAccessToken: AccessToken.current!.tokenString)
    FIRAuthCredential *credential = [FIRFacebookAuthProvider
        credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];

Implementowanie ograniczonego logowania na Facebooku

Aby zamiast „klasycznego” logowania na Facebooku używać logowania ograniczonego, wykonaj te czynności.

  1. Zintegruj logowanie Facebooka w swojej aplikacji, postępując zgodnie z  dokumentacją dla deweloperów.
  2. W przypadku każdego żądania logowania wygeneruj unikalny losowy ciąg znaków (zwany „nonce”), który posłuży Ci do sprawdzenia, czy otrzymany token tożsamości został przyznany w odpowiedzi na żądanie uwierzytelniania aplikacji. Ten krok jest ważny, ponieważ zapobiega atakom metodą powtórzenia. Możesz wygenerować bezpieczny kryptograficznie nonce za pomocą funkcji SecRandomCopyBytes(_:_:_), jak w tym przykładzie:
    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)
    }
    
            
    // 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];
    }
            
    Wraz z żądaniem logowania wyślesz hasz SHA-256 nonce, który Facebook przekaże w odpowiedzi bez zmian. Firebase weryfikuje odpowiedź, szyfrując pierwotny identyfikator jednorazowy i porównując go z wartością przekazaną przez Facebooka.
    @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
    }
    
            
    - (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 usługi FBSDKLoginButton ustaw delegowanie, aby otrzymywać zdarzenia logowania i wylogowywania, ustaw tryb śledzenia na FBSDKLoginTrackingLimited i dołącz losowy ciąg znaków. Przykład:
    func setupLoginButton() {
        let nonce = randomNonceString()
        currentNonce = nonce
        loginButton.delegate = self
        loginButton.loginTracking = .limited
        loginButton.nonce = sha256(nonce)
    }
            
    - (void)setupLoginButton {
      NSString *nonce = [self randomNonce:32];
      self.currentNonce = nonce;
      self.loginButton.delegate = self;
      self.loginButton.loginTracking = FBSDKLoginTrackingLimited
      self.loginButton.nonce = [self stringBySha256HashingString:nonce];
    }
            
    W ramach delegowania implementuj didCompleteWithResult:error:.
    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
      if let error = error {
        print(error.localizedDescription)
        return
      }
      // ...
    }
            
    - (void)loginButton:(FBSDKLoginButton *)loginButton
        didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
                        error:(NSError *)error {
      if (error == nil) {
        // ...
      } else {
        NSLog(error.localizedDescription);
      }
    }
            
  4. Zaimportuj moduł FirebaseCore w pliku UIApplicationDelegate, a także wszystkie inne moduły Firebase, których używa delegowany obiekt aplikacji. Aby na przykład użyć właściwości Cloud FirestoreAuthentication:
    import SwiftUI
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          
    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  5. Skonfiguruj współdzieloną instancję FirebaseApp w metodzie application(_:didFinishLaunchingWithOptions:) w delegacie aplikacji:
    // Use Firebase library to configure APIs
    FirebaseApp.configure()
    // Use Firebase library to configure APIs
    FirebaseApp.configure()
    // Use Firebase library to configure APIs
    [FIRApp configure];
  6. Jeśli używasz SwiftUI, musisz utworzyć obiekt delegujący aplikacji i dołączyć go do struktury App za pomocą funkcji UIApplicationDelegateAdaptor lub NSApplicationDelegateAdaptor. Musisz też wyłączyć swizlowanie zastępników aplikacji. Więcej informacji znajdziesz w instrukcjach dotyczących 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. Po zalogowaniu się użytkownika w ramach implementacji didCompleteWithResult:error: użyj tokena ID z odpowiedzi Facebooka z niezaszyfrowanym identyfikatorem jednorazowym, aby uzyskać dane logowania Firebase:
    // Initialize a Firebase credential.
    let idTokenString = AuthenticationToken.current?.tokenString
    let nonce = currentNonce
    let credential = OAuthProvider.credential(withProviderID: "facebook.com",
                                              idToken: idTokenString!,
                                              rawNonce: nonce)
            
    // Initialize a Firebase credential.
    NSString *idTokenString = FBSDKAuthenticationToken.currentAuthenticationToken.tokenString;
    NSString *rawNonce = self.currentNonce;
    FIROAuthCredential *credential = [FIROAuthProvider credentialWithProviderID:@"facebook.com"
                                                                        IDToken:idTokenString
                                                                       rawNonce:rawNonce];
            

Uwierzytelnienie za pomocą Firebase

Na koniec uwierzytelnij się w Firebase, używając danych logowania Firebase:

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
    // ...
}
    
[[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, zostanie utworzone nowe konto użytkownika i połączone z danymi logowania, czyli nazwą użytkownika i hasłem, numerem telefonu lub informacjami dostawcy uwierzytelniania. To nowe konto jest przechowywane w projekcie Firebase i może służyć do identyfikowania użytkownika we wszystkich aplikacjach w projekcie, niezależnie od tego, jak użytkownik się loguje.

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

  • W regułach Firebase Realtime DatabaseCloud Storage Regułach bezpieczeństwa możesz pobrać z zmiennej auth unikalny identyfikator zalogowanego użytkownika i użyć go do kontrolowania dostępu użytkownika do danych.

Możesz zezwolić użytkownikom na logowanie się w aplikacji za pomocą danych logowania od wielu dostawców uwierzytelniania, połączając je z dotychczasowym kontem użytkownika.

Aby wylogować użytkownika, zadzwoń pod numer 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żesz też dodać kod do obsługi błędów w całym zakresie błędów uwierzytelniania. Zobacz Obsługa błędów.

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.

Aktualizacja: Mar 7, 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.

Aktualizacja: Mar 7, 2025