ลิงก์ผู้ให้บริการการตรวจสอบสิทธิ์หลายรายกับบัญชีบนแพลตฟอร์ม Apple

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

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

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

วิธีลิงก์ข้อมูลเข้าสู่ระบบของผู้ให้บริการตรวจสอบสิทธิ์กับบัญชีผู้ใช้ที่มีอยู่

  1. ลงชื่อเข้าใช้ผู้ใช้โดยใช้ผู้ให้บริการหรือวิธีการตรวจสอบสิทธิ์ใดก็ได้
  2. ดำเนินการตามขั้นตอนการลงชื่อเข้าใช้ของผู้ให้บริการการตรวจสอบสิทธิ์รายใหม่จนเสร็จสิ้น แต่ไม่ใช่ ซึ่งรวมถึงการเรียกหนึ่งในเมธอด FIRAuth.signInWith เช่น ดู โทเค็น Google ID, โทเค็นเพื่อการเข้าถึง Facebook หรืออีเมลและรหัสผ่านของผู้ใช้
  3. รับ FIRAuthCredential สำหรับผู้ให้บริการตรวจสอบสิทธิ์รายใหม่:

    Google Sign-In
    SwiftObjective-C
    guard
      let authentication = user?.authentication,
      let idToken = authentication.idToken
    else {
      return
    }
    
    let credential = GoogleAuthProvider.credential(withIDToken: idToken,
                                                   accessToken: authentication.accessToken)
    FIRAuthCredential *credential =
    [FIRGoogleAuthProvider credentialWithIDToken:result.user.idToken.tokenString
                                     accessToken:result.user.accessToken.tokenString];
    เข้าสู่ระบบ Facebook
    SwiftObjective-C
    let credential = FacebookAuthProvider
      .credential(withAccessToken: AccessToken.current!.tokenString)
    FIRAuthCredential *credential = [FIRFacebookAuthProvider
        credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];
    การลงชื่อเข้าใช้ด้วยอีเมลด้วยรหัสผ่าน
    SwiftObjective-C
    let credential = EmailAuthProvider.credential(withEmail: email, password: password)
    FIRAuthCredential *credential =
        [FIREmailAuthProvider credentialWithEmail:email
                                                 password:password];
  4. ส่งออบเจ็กต์ FIRAuthCredential ไปยังผู้ใช้ที่ลงชื่อเข้าใช้ เมธอด linkWithCredential:completion::

    SwiftObjective-C
        user.link(with: credential) { authResult, error in
      // ...
    }
    }
        [[FIRAuth auth].currentUser linkWithCredential:credential
        completion:^(FIRAuthDataResult *result, NSError *_Nullable error) {
      // ...
    }];

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

    SwiftObjective-C
    let prevUser = Auth.auth().currentUser
    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
        // ...
    }
                // Merge prevUser and currentUser accounts and data
                // ...
            }
    FIRUser *prevUser = [FIRAuth auth].currentUser;
    [[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;
      // ...
    }];
                                        // Merge prevUser and currentUser accounts and data
                                        // ...
                                    }];

หากโทรหา linkWithCredential:completion: สำเร็จ ผู้ใช้จะสามารถลงชื่อเข้าใช้โดยใช้ ผู้ให้บริการการตรวจสอบสิทธิ์ที่ลิงก์อยู่รายใดก็ได้ และเข้าถึงข้อมูล Firebase เดียวกัน

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

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

SwiftObjective-C
Auth.auth().currentUser?.unlink(fromProvider: providerID!) { user, error in
  // ...
}
[[FIRAuth auth].currentUser unlinkFromProvider:providerID
                                    completion:^(FIRUser *_Nullable user, NSError *_Nullable error) {
  // ...
}];

Firebase gives you the tools and infrastructure you need to build better mobile and web apps, improve app quality, and grow your business.

อัปเดตแล้ว Feb 28, 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.

อัปเดตแล้ว Feb 28, 2025