ตรวจสอบสิทธิ์โดยใช้การเข้าสู่ระบบ Facebook บนแพลตฟอร์ม Apple

คุณอนุญาตให้ผู้ใช้ตรวจสอบสิทธิ์ด้วย Firebase โดยใช้บัญชี Facebook ได้ โดยการผสานรวมการเข้าสู่ระบบด้วย Facebook หรือการเข้าสู่ระบบด้วย Facebook แบบจำกัดเข้ากับแอป

ก่อนเริ่มต้น

ใช้ Swift Package Manager เพื่อติดตั้งและจัดการทรัพยากร Dependency ของ Firebase

  1. เปิดโปรเจ็กต์แอปใน Xcode แล้วไปที่File > Add Packages
  2. เมื่อได้รับข้อความแจ้ง ให้เพิ่มที่เก็บ SDK ของแพลตฟอร์ม Apple ของ Firebase ดังนี้
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. เลือกFirebase Authentication คลัง
  5. เพิ่มแฟล็ก -ObjC ลงในส่วนแฟล็ก Linker อื่นๆ ของการตั้งค่าบิลด์ของเป้าหมาย
  6. เมื่อเสร็จแล้ว Xcode จะเริ่มจับคู่ข้อมูลและดาวน์โหลดทรัพยากร Dependency ในเบื้องหลังโดยอัตโนมัติ

จากนั้น ให้ทำตามขั้นตอนการกำหนดค่าต่อไปนี้

  1. ในเว็บไซต์ Facebook for Developers ให้รับ App ID และ App Secret สำหรับแอปของคุณ
  2. วิธีเปิดใช้การเข้าสู่ระบบด้วย Facebook
    1. เปิดส่วนการตรวจสอบสิทธิ์ในคอนโซล Firebase
    2. ในแท็บวิธีการลงชื่อเข้าใช้ ให้เปิดใช้Facebook และระบุรหัสแอปและข้อมูลลับของแอปที่คุณได้รับจาก Facebook
    3. จากนั้นตรวจสอบว่า URI การเปลี่ยนเส้นทาง OAuth (เช่น my-app-12345.firebaseapp.com/__/auth/handler) แสดงเป็นหนึ่งใน URI การเปลี่ยนเส้นทาง OAuth ในหน้าการตั้งค่าของแอป Facebook บนเว็บไซต์ Facebook for Developers ใน การกำหนดค่าการตั้งค่าผลิตภัณฑ์ > Facebook Login

ใช้ Facebook Login

หากต้องการใช้การเข้าสู่ระบบด้วย Facebook แบบ "คลาสสิก" ให้ทำตามขั้นตอนต่อไปนี้ หรือคุณจะใช้การเข้าสู่ระบบแบบจำกัดของ Facebook ก็ได้ ดังที่แสดงในส่วนถัดไป

  1. ผสานรวมการเข้าสู่ระบบด้วย Facebook เข้ากับแอปโดยทำตาม เอกสารประกอบสำหรับนักพัฒนาซอฟต์แวร์ เมื่อเริ่มต้นออบเจ็กต์ 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. นำเข้าโมดูล FirebaseCore ใน UIApplicationDelegate รวมถึงโมดูล Firebase อื่นๆ ที่ตัวแทนแอปของคุณใช้ เช่น หากต้องการใช้ Cloud Firestore และ Authentication ให้ทำดังนี้

    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. กำหนดค่า FirebaseApp อินสแตนซ์ที่แชร์ใน 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. หากใช้ SwiftUI คุณต้องสร้างตัวแทนแอปพลิเคชันและแนบไปกับโครงสร้าง App ผ่าน UIApplicationDelegateAdaptor หรือ NSApplicationDelegateAdaptor นอกจากนี้ คุณยังต้องปิดใช้การสลับแทนของตัวแทนแอปด้วย ดูข้อมูลเพิ่มเติมได้ที่วิธีการสำหรับ 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. หลังจากที่ผู้ใช้ลงชื่อเข้าใช้สำเร็จแล้ว ในการติดตั้งใช้งาน didCompleteWithResult:error: ให้รับโทเค็นเพื่อการเข้าถึงสำหรับ ผู้ใช้ที่ลงชื่อเข้าใช้ และแลกเป็นข้อมูลเข้าสู่ระบบ Firebase โดยทำดังนี้

    Swift

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

    Objective-C

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

ใช้การเข้าสู่ระบบแบบจำกัดของ Facebook

หากต้องการใช้การเข้าสู่ระบบ Facebook แบบจำกัดแทนการเข้าสู่ระบบ Facebook "คลาสสิก" ให้ทำตามขั้นตอนต่อไปนี้

  1. ผสานรวมการเข้าสู่ระบบแบบจำกัดของ Facebook เข้ากับแอปโดยทำตาม เอกสารประกอบสำหรับนักพัฒนาซอฟต์แวร์
  2. สำหรับคำขอลงชื่อเข้าใช้ทุกรายการ ให้สร้างสตริงแบบสุ่มที่ไม่ซ้ำกัน ซึ่งก็คือ "Nonce" ซึ่ง คุณจะใช้เพื่อให้แน่ใจว่าโทเค็นรหัสที่คุณได้รับนั้นได้รับอนุญาตเฉพาะใน การตอบกลับคำขอการตรวจสอบสิทธิ์ของแอป ขั้นตอนนี้สำคัญต่อการ ป้องกันการโจมตีแบบรีเพลย์ คุณสร้าง Nonce ที่ปลอดภัยด้วยการเข้ารหัสลับได้โดยใช้ 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 พร้อมกับคำขอลงชื่อเข้าใช้ ซึ่ง Facebook จะส่งต่อโดยไม่มีการเปลี่ยนแปลงในคำตอบ Firebase จะตรวจสอบการตอบกลับโดยแฮช Nonce เดิมและเปรียบเทียบกับค่าที่ Facebook ส่งมา

    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 และแนบ Nonce เช่น

    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. นำเข้าโมดูล FirebaseCore ใน UIApplicationDelegate รวมถึงโมดูล Firebase อื่นๆ ที่ตัวแทนแอปของคุณใช้ เช่น หากต้องการใช้ Cloud Firestore และ Authentication ให้ทำดังนี้

    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. กำหนดค่า FirebaseApp อินสแตนซ์ที่แชร์ใน 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. หากใช้ SwiftUI คุณต้องสร้างตัวแทนแอปพลิเคชันและแนบไปกับโครงสร้าง App ผ่าน UIApplicationDelegateAdaptor หรือ NSApplicationDelegateAdaptor นอกจากนี้ คุณยังต้องปิดใช้การสลับแทนของตัวแทนแอปด้วย ดูข้อมูลเพิ่มเติมได้ที่วิธีการสำหรับ 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. หลังจากที่ผู้ใช้ลงชื่อเข้าใช้สำเร็จแล้ว ในการติดตั้งใช้งาน didCompleteWithResult:error: ให้ใช้โทเค็นรหัสจากคำตอบของ Facebook พร้อมกับ Nonce ที่ไม่ได้แฮชเพื่อรับข้อมูลเข้าสู่ระบบ 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];
            

ตรวจสอบสิทธิ์ด้วย Firebase

สุดท้าย ให้ตรวจสอบสิทธิ์ด้วย Firebase โดยใช้ข้อมูลเข้าสู่ระบบ 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;
  // ...
}];
    

ขั้นตอนถัดไป

หลังจากที่ผู้ใช้ลงชื่อเข้าใช้เป็นครั้งแรก ระบบจะสร้างบัญชีผู้ใช้ใหม่และ ลิงก์กับข้อมูลเข้าสู่ระบบ ซึ่งได้แก่ ชื่อผู้ใช้และรหัสผ่าน หมายเลขโทรศัพท์ หรือข้อมูลผู้ให้บริการตรวจสอบสิทธิ์ที่ผู้ใช้ลงชื่อเข้าใช้ ระบบจะจัดเก็บบัญชีใหม่นี้เป็นส่วนหนึ่งของโปรเจ็กต์ Firebase และสามารถใช้เพื่อระบุตัวตน ผู้ใช้ในทุกแอปในโปรเจ็กต์ได้ ไม่ว่าผู้ใช้จะลงชื่อเข้าใช้ด้วยวิธีใดก็ตาม

  • ในแอป คุณจะดูข้อมูลโปรไฟล์พื้นฐานของผู้ใช้ได้จากออบเจ็กต์ User ดูจัดการผู้ใช้

  • ใน Firebase Realtime Database และ Cloud Storage กฎความปลอดภัย คุณสามารถ รับรหัสผู้ใช้ที่ไม่ซ้ำของผู้ใช้ที่ลงชื่อเข้าใช้จากตัวแปร auth และใช้รหัสดังกล่าวเพื่อควบคุมข้อมูลที่ผู้ใช้เข้าถึงได้

คุณอนุญาตให้ผู้ใช้ลงชื่อเข้าใช้แอปโดยใช้ผู้ให้บริการตรวจสอบสิทธิ์หลายรายได้โดยลิงก์ข้อมูลเข้าสู่ระบบของผู้ให้บริการตรวจสอบสิทธิ์กับบัญชีผู้ใช้ที่มีอยู่

หากต้องการออกจากระบบของผู้ใช้ ให้เรียกใช้ 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;
}

นอกจากนี้ คุณอาจต้องเพิ่มโค้ดการจัดการข้อผิดพลาดสำหรับการตรวจสอบสิทธิ์ ทั้งหมดด้วย ดูจัดการข้อผิดพลาด