Xác thực bằng tính năng đăng nhập Facebook trên các nền tảng của Apple

Bạn có thể cho phép người dùng xác thực với Firebase thông qua tài khoản Facebook của họ bằng cách tích hợp tính năng Đăng nhập bằng Facebook hoặc Đăng nhập có giới hạn bằng Facebook vào ứng dụng của mình.

Trước khi bắt đầu

Sử dụng Trình quản lý gói Swift để cài đặt và quản lý các phần phụ thuộc Firebase.

  1. Trong Xcode, khi dự án ứng dụng của bạn đang mở, hãy chuyển đến File > Add Packages (Tệp > Thêm gói).
  2. Khi được nhắc, hãy thêm kho lưu trữ SDK nền tảng Apple của Firebase:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. Chọn thư viện Xác thực Firebase.
  5. Thêm cờ -ObjC vào mục Cờ trình liên kết khác trong chế độ cài đặt bản dựng của mục tiêu.
  6. Khi hoàn tất, Xcode sẽ tự động bắt đầu phân giải và tải các phần phụ thuộc của bạn xuống ở chế độ nền.

Tiếp theo, hãy thực hiện một số bước định cấu hình:

  1. Trên trang web Facebook for Developers, hãy lấy ID ứng dụngApp Secret cho ứng dụng của bạn.
  2. Bật tính năng đăng nhập Facebook:
    1. Trong bảng điều khiển của Firebase, hãy mở phần Xác thực.
    2. Trên thẻ Sign in method (Phương thức đăng nhập), hãy bật phương thức đăng nhập Facebook và chỉ định App IDApp Secret mà bạn nhận được từ Facebook.
    3. Sau đó, hãy đảm bảo URI chuyển hướng OAuth (ví dụ: my-app-12345.firebaseapp.com/__/auth/handler) được liệt kê là một trong các URI chuyển hướng OAuth trong trang cài đặt của ứng dụng Facebook trên trang web Facebook for Developers trong cấu hình Product Settings > Facebook Đăng nhập.

Triển khai Đăng nhập Facebook

Để sử dụng tính năng Đăng nhập Facebook "cũ", hãy hoàn tất các bước sau. Ngoài ra, bạn có thể sử dụng tính năng Đăng nhập có giới hạn trên Facebook, như minh hoạ trong phần tiếp theo.

  1. Tích hợp tính năng Đăng nhập bằng Facebook vào ứng dụng của bạn bằng cách làm theo tài liệu của nhà phát triển. Khi bạn khởi tạo đối tượng FBSDKLoginButton, hãy thiết lập một thực thể uỷ quyền để nhận các sự kiện đăng nhập và đăng xuất. Ví dụ:

    Swift

    let loginButton = FBSDKLoginButton()
    loginButton.delegate = self
    

    Objective-C

    FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
    loginButton.delegate = self;
    
    Trong thực thể uỷ quyền, hãy triển khai 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. Nhập mô-đun FirebaseCore trong UIApplicationDelegate, cũng như bất kỳ mô-đun Firebase nào khác mà đại diện ứng dụng của bạn sử dụng. Ví dụ: Cách sử dụng Cloud Firestore và Xác thực:

    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. Định cấu hình một thực thể dùng chung của FirebaseApp trong phương thức application(_:didFinishLaunchingWithOptions:) của uỷ quyền ứng dụng:

    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. Nếu đang sử dụng SwiftUI, bạn phải tạo một ứng dụng uỷ quyền và đính kèm ứng dụng đó vào cấu trúc App thông qua UIApplicationDelegateAdaptor hoặc NSApplicationDelegateAdaptor. Bạn cũng phải tắt tính năng uỷ quyền ứng dụng. Để biết thêm thông tin, hãy xem hướng dẫn về 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. Sau khi người dùng đăng nhập thành công, trong quá trình triển khai didCompleteWithResult:error:, hãy lấy mã truy cập của người dùng đã đăng nhập và đổi mã đó lấy thông tin đăng nhập Firebase:

    Swift

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

    Objective-C

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

Triển khai tính năng Đăng nhập giới hạn trên Facebook

Để sử dụng tính năng Đăng nhập có giới hạn bằng Facebook thay vì tính năng Đăng nhập Facebook "kiểu cũ", hãy hoàn tất các bước sau.

  1. Tích hợp tính năng Đăng nhập bằng Facebook Limited vào ứng dụng của bạn bằng cách làm theo tài liệu của nhà phát triển.
  2. Đối với mỗi yêu cầu đăng nhập, hãy tạo một chuỗi ngẫu nhiên duy nhất – "số chỉ dùng một lần" – mà bạn sẽ dùng để đảm bảo mã thông báo mã nhận dạng mà bạn nhận được đã được cấp riêng theo yêu cầu xác thực của ứng dụng. Đây là bước quan trọng để ngăn chặn các cuộc tấn công phát lại. Bạn có thể tạo một số chỉ dùng một lần được bảo mật được mã hoá bằng SecRandomCopyBytes(_:_:_), như trong ví dụ sau:

    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];
    }
            
    Bạn sẽ gửi hàm băm SHA-256 của số chỉ dùng một lần cùng với yêu cầu đăng nhập. Facebook sẽ không thay đổi nội dung này trong phản hồi. Firebase xác thực phản hồi bằng cách băm số chỉ dùng một lần ban đầu rồi so sánh với giá trị mà Facebook chuyển.

    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. Khi bạn thiết lập FBSDKLoginButton, hãy đặt một thực thể đại diện để nhận các sự kiện đăng nhập và đăng xuất, đặt chế độ theo dõi thành FBSDKLoginTrackingLimited và đính kèm một số chỉ dùng một lần. Ví dụ:

    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];
    }
            
    Trong thực thể uỷ quyền, hãy triển khai 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. Nhập mô-đun FirebaseCore trong UIApplicationDelegate, cũng như bất kỳ mô-đun Firebase nào khác mà đại diện ứng dụng của bạn sử dụng. Ví dụ: Cách sử dụng Cloud Firestore và Xác thực:

    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. Định cấu hình một thực thể dùng chung của FirebaseApp trong phương thức application(_:didFinishLaunchingWithOptions:) của uỷ quyền ứng dụng:

    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. Nếu đang sử dụng SwiftUI, bạn phải tạo một ứng dụng uỷ quyền và đính kèm ứng dụng đó vào cấu trúc App thông qua UIApplicationDelegateAdaptor hoặc NSApplicationDelegateAdaptor. Bạn cũng phải tắt tính năng uỷ quyền ứng dụng. Để biết thêm thông tin, hãy xem hướng dẫn về 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. Sau khi người dùng đăng nhập thành công, trong quá trình triển khai didCompleteWithResult:error:, hãy sử dụng mã thông báo nhận dạng trong phản hồi của Facebook cùng với số chỉ dùng một lần chưa được băm để lấy thông tin đăng nhập 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];
            

Xác thực bằng Firebase

Cuối cùng, hãy xác thực với Firebase bằng thông tin đăng nhập 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;
  // ...
}];
    

Các bước tiếp theo

Sau khi người dùng đăng nhập lần đầu tiên, một tài khoản người dùng mới sẽ được tạo và liên kết với thông tin đăng nhập (chẳng hạn như tên người dùng và mật khẩu, số điện thoại hoặc thông tin của nhà cung cấp dịch vụ xác thực) mà người dùng đã đăng nhập. Tài khoản mới này được lưu trữ như một phần trong dự án Firebase và có thể được dùng để xác định người dùng trên mọi ứng dụng trong dự án của bạn, bất kể người dùng đăng nhập bằng cách nào.

  • Trong các ứng dụng, bạn có thể lấy thông tin hồ sơ cơ bản của người dùng từ đối tượng User . Xem phần Quản lý người dùng.

  • Trong Quy tắc bảo mật của Cloud Storage và Cơ sở dữ liệu theo thời gian thực của Firebase, bạn có thể lấy mã nhận dạng người dùng riêng biệt của người dùng đã đăng nhập từ biến auth rồi sử dụng mã này để kiểm soát những dữ liệu mà người dùng có thể truy cập.

Bạn có thể cho phép người dùng đăng nhập vào ứng dụng của mình thông qua nhiều nhà cung cấp dịch vụ xác thực bằng cách liên kết thông tin đăng nhập của nhà cung cấp dịch vụ xác thực với một tài khoản người dùng hiện có.

Để đăng xuất một người dùng, hãy gọi 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;
}

Bạn cũng nên thêm mã xử lý lỗi cho toàn bộ các lỗi xác thực. Hãy xem bài viết Xử lý lỗi.