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

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

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

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

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

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

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

ใช้ฟีเจอร์เข้าสู่ระบบด้วย Facebook

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

  1. ผสานรวมฟีเจอร์เข้าสู่ระบบด้วย Facebook เข้ากับแอปโดยทําตาม เอกสารประกอบสําหรับนักพัฒนาแอป เมื่อเริ่มต้นออบเจ็กต์ FBSDKLoginButton ให้ตั้งค่าผู้รับมอบสิทธิ์เพื่อรับเหตุการณ์การเข้าสู่ระบบและการออกจากระบบ เช่น
    SwiftObjective-C
    let loginButton = FBSDKLoginButton()
    loginButton.delegate = self
    FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
    loginButton.delegate = self;
    ติดตั้งใช้งาน didCompleteWithResult:error: ในผู้รับมอบสิทธิ์
    SwiftObjective-C
    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. นําเข้าโมดูล FirebaseCore ใน UIApplicationDelegate รวมถึงโมดูล Firebase อื่นๆ ที่ผู้รับมอบสิทธิ์ของแอปใช้ ตัวอย่างเช่น หากต้องการใช้ Cloud Firestore และ Authentication ให้ทำดังนี้
    SwiftUISwiftObjective-C
    import SwiftUI
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          
    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  3. กำหนดค่าอินสแตนซ์ที่แชร์ในเมธอด application(_:didFinishLaunchingWithOptions:) ของตัวแทนแอป ดังนี้ FirebaseApp
    SwiftUISwiftObjective-C
    // 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. หากใช้ SwiftUI คุณต้องสร้างผู้รับมอบสิทธิ์แอปพลิเคชันและแนบไปกับ App struct ผ่าน 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 โดยทําดังนี้
    SwiftObjective-C
    let credential = FacebookAuthProvider
      .credential(withAccessToken: AccessToken.current!.tokenString)
    FIRAuthCredential *credential = [FIRFacebookAuthProvider
        credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];

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

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

  1. ผสานรวมการเข้าสู่ระบบแบบจำกัดของ Facebook เข้ากับแอปโดยทําตาม เอกสารประกอบสําหรับนักพัฒนาแอป
  2. สําหรับคําขอลงชื่อเข้าใช้แต่ละรายการ ให้สร้างสตริงแบบสุ่มที่ไม่ซ้ำกัน ซึ่งก็คือ "Nonce" ที่คุณจะใช้เพื่อตรวจสอบว่าโทเค็นระบุตัวตนที่ได้รับนั้นได้รับอนุญาตโดยเฉพาะเพื่อตอบสนองคําขอตรวจสอบสิทธิ์ของแอป ขั้นตอนนี้สำคัญต่อการป้องกันการโจมตีด้วยการเล่นซ้ำ คุณสามารถสร้าง Nonce ที่ปลอดภัยตามวิทยาการเข้ารหัสด้วย SecRandomCopyBytes(_:_:_) ดังตัวอย่างต่อไปนี้
    SwiftObjective-C
    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];
    }
            
    คุณจะส่งแฮช SHA-256 ของ Nonce ไปพร้อมกับคําขอลงชื่อเข้าใช้ ซึ่ง Facebook จะส่งต่อโดยไม่เปลี่ยนแปลงในคําตอบ Firebase จะตรวจสอบการตอบกลับโดยการแฮช Nonce เดิมและเปรียบเทียบกับค่าที่ Facebook ส่ง
    SwiftObjective-C
    @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. เมื่อตั้งค่า FBSDKLoginButton ให้ตั้งค่าผู้รับมอบสิทธิ์ให้รับเหตุการณ์การเข้าสู่ระบบและการออกจากระบบ ตั้งค่าโหมดการติดตามเป็น FBSDKLoginTrackingLimited และแนบ Nonce เช่น
    SwiftObjective-C
    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];
    }
            
    ติดตั้งใช้งาน didCompleteWithResult:error: ในผู้รับมอบสิทธิ์
    SwiftObjective-C
    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. นําเข้าโมดูล FirebaseCore ใน UIApplicationDelegate รวมถึงโมดูล Firebase อื่นๆ ที่ผู้รับมอบสิทธิ์ของแอปใช้ ตัวอย่างเช่น หากต้องการใช้ Cloud Firestore และ Authentication ให้ทำดังนี้
    SwiftUISwiftObjective-C
    import SwiftUI
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          
    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  5. กำหนดค่าอินสแตนซ์ที่แชร์ในเมธอด application(_:didFinishLaunchingWithOptions:) ของตัวแทนแอป ดังนี้ FirebaseApp
    SwiftUISwiftObjective-C
    // 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. หากใช้ SwiftUI คุณต้องสร้างผู้รับมอบสิทธิ์แอปพลิเคชันและแนบไปกับ App struct ผ่าน 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 โดยทำดังนี้
    SwiftObjective-C
    // 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];
            

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

สุดท้าย ให้ตรวจสอบสิทธิ์กับ Firebase โดยใช้ข้อมูลเข้าสู่ระบบ Firebase โดยทำดังนี้

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

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

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

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

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

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

หากต้องการออกจากระบบของผู้ใช้ ให้โทร signOut:

SwiftObjective-C
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;
}

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