כניסה לחשבון באמצעות Facebook ב-iOS

אתם יכולים לאפשר למשתמשים שלכם להתאמת באמצעות Identity Platform באמצעות חשבונות הפייסבוק שלהם, על ידי שילוב של התחברות באמצעות פייסבוק או התחברות מוגבלת באמצעות פייסבוק באפליקציה שלכם. בדף הזה מוסבר איך להשתמש ב-Identity Platform כדי להוסיף לאפליקציית iOS את האפשרות 'כניסה באמצעות פייסבוק'.

לפני שמתחילים

  1. איך מוסיפים את Firebase לפרויקט iOS

  2. כוללים את ה-Pods הבאים ב-Podfile:

    pod 'FirebaseAuth'
    
  3. נכנסים לדף Identity Providers במסוף Google Cloud .

    כניסה לדף Identity Providers

  4. לוחצים על הוספת ספק.

  5. בוחרים באפשרות Facebook מהרשימה.

  6. מזינים את מזהה האפליקציה ואת סוד האפליקציה ב-Facebook. אם עדיין אין לכם מזהה וסוד, תוכלו לקבל אותם מהדף Facebook for Developers.

  7. מגדירים את ה-URI שמופיע בקטע הגדרה של פייסבוק כ-URI תקף להפניה אוטומטית של OAuth באפליקציית פייסבוק. אם הגדרתם דומיין בהתאמה אישית ב-Identity Platform, צריך לעדכן את ה-URI להפניה אוטומטית בהגדרות של אפליקציית פייסבוק כדי להשתמש בדומיין המותאם אישית במקום בדומיין שמוגדר כברירת מחדל. לדוגמה, שינוי של https://myproject.firebaseapp.com/__/auth/handler ל-https://auth.myownpersonaldomain.com/__/auth/handler.

  8. לוחצים על הוספת דומיין בקטע דומיינים מורשים כדי לרשום את הדומיינים של האפליקציה. למטרות פיתוח, localhost כבר מופעל כברירת מחדל.

  9. בקטע הגדרת האפליקציה, לוחצים על פרטי ההגדרה. מעתיקים את קטע הקוד לקוד של האפליקציה כדי להפעיל את Identity Platform client SDK.

  10. לוחצים על Save.

הטמעה של התחברות באמצעות חשבון Facebook

כדי להשתמש בגרסה הקלאסית של התכונה 'כניסה באמצעות פייסבוק', צריך לבצע את השלבים הבאים. אפשרות אחרת היא להשתמש בכניסה מוגבלת של פייסבוק, כמו שמוצג בקטע הבא.

  1. כדי לשלב את התכונה 'כניסה באמצעות פייסבוק' באפליקציה, פועלים לפי התיעוד למפתחים. כשמאתחלים את האובייקט FBSDKLoginButton, מגדירים נציג לקבלת אירועי כניסה ויציאה. לדוגמה:

    Swift

    let loginButton = FBSDKLoginButton()
    loginButton.delegate = self

    Objective-C

    FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
    loginButton.delegate = self;
    בנציג, מטמיעים את didCompleteWithResult:error:.

    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. מייבאים את מודול Firebase אל UIApplicationDelegate:

    Swift

    import FirebaseCore
    import FirebaseAuth
          

    Objective-C

    @import FirebaseCore;
    @import FirebaseAuth;
          
  3. מגדירים מופע משותף של FirebaseApp, בדרך כלל בשיטה application:didFinishLaunchingWithOptions: של האפליקציה:

    Swift

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

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
  4. אחרי שהמשתמש מתחבר בהצלחה, בהטמעה של didCompleteWithResult:error:, מקבלים אסימון גישה למשתמש המחובר ומחליפים אותו בפרטי כניסה של Identity Platform:

    Swift

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

    Objective-C

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

הטמעה של התכונה 'כניסה מוגבלת' של פייסבוק

כדי להשתמש בכניסה מוגבלת של פייסבוק במקום בכניסה 'קלאסית' של פייסבוק, צריך לבצע את השלבים הבאים.

  1. כדי לשלב את הכניסה המוגבלת של פייסבוק באפליקציה, פועלים לפי התיעוד למפתחים.
  2. לכל בקשת כניסה, יוצרים מחרוזת אקראית ייחודית – 'צופן חד-פעמי (nonce)' – שבה תשתמשו כדי לוודא שאסימון המזהה שקיבלתם הוענק בתגובה ספציפית לבקשת האימות של האפליקציה. השלב הזה חשוב כדי למנוע התקפות שליחה מחדש. אפשר ליצור צופן חד-פעמי (nonce) מאובטח מבחינה קריפטוגרפית ב-iOS באמצעות SecRandomCopyBytes(_:_:_), כמו בדוגמה הבאה:

    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];
    }
            
    תשלחו את גיבוב SHA-256 של ה-nonce עם בקשת הכניסה, ופייסבוק תעביר אותו ללא שינוי בתשובה. ‫Identity Platform מאמת את התגובה על ידי גיבוב של ה-nonce המקורי והשוואה שלו לערך שמועבר על ידי פייסבוק.

    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. כשמגדירים את FBSDKLoginButton, צריך להגדיר נציג שיקבל אירועי כניסה ויציאה, להגדיר את מצב המעקב ל-FBSDKLoginTrackingLimited ולצרף ערך חד-פעמי. לדוגמה:

    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];
    }
            
    בנציג, מטמיעים את didCompleteWithResult:error:.

    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. מייבאים את מודול Firebase אל UIApplicationDelegate:

    Swift

    import Firebase

    Objective-C

    @import Firebase;
  5. מגדירים מופע משותף של FirebaseApp, בדרך כלל בשיטה application:didFinishLaunchingWithOptions: של האפליקציה:

    Swift

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

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
  6. אחרי שהמשתמש נכנס בהצלחה, בהטמעה של didCompleteWithResult:error:, משתמשים באסימון הזהות מהתגובה של פייסבוק עם ה-nonce שלא עבר גיבוב כדי לקבל אישור מ-Identity Platform:

    Swift

    // Initialize an Identity Platform credential.
    let idTokenString = AuthenticationToken.current?.tokenString
    let nonce = currentNonce
    let credential = OAuthProvider.credential(withProviderID: "facebook.com",
                                              IDToken: idTokenString,
                                              rawNonce: nonce)
            

    Objective-C

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

אימות באמצעות Identity Platform

לבסוף, מבצעים אימות באמצעות Identity Platform באמצעות פרטי הכניסה של Identity Platform:

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

המאמרים הבאים