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 bằng tài khoản Facebook của họ bằng cách tích hợp tính năng Đăng nhập Facebook hoặc Đăng nhập có giới hạn trên Facebook vào ứng dụng của bạn.

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 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 xuống các phần phụ thuộc trong nền.

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

  1. Trên Facebook for Developers trang web, hãy lấy Mã ứng dụngKhoá bí mật ứng dụng cho ứng dụng của bạn.
  2. Bật đă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 tính năng đăng nhập Facebook và chỉ định ID ứng dụngBí mật ứng dụng 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ài đặt sản phẩm > Cấu hình Đăng nhập Facebook.

Triển khai Đăng nhập Facebook

Để sử dụng từ "cổ điển" Đăng nhập Facebook, 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ư được trình bày trong phần tiếp theo.

  1. Tích hợp Đăng nhập 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 chạy FBSDKLoginButton, hãy thiết lập một uỷ quyền để nhận thông tin đăng nhập và sự kiện đă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ỳ tên nào khác Các mô-đun Firebase mà người được uỷ quyề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 FirebaseApp thực thể dùng chung trong Phương thức 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. 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 nó đến cấu trúc App của bạn 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. Cho hãy xem hướng dẫn về SwiftUI để biết thêm thông tin.

    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 nhận mã truy cập cho người dùng đã đăng nhập và đổi 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 trên Facebook thay vì "kiểu cũ" Đăng nhập Facebook, hoàn tất các bước sau đây.

  1. Tích hợp tính năng Đăng nhập 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 – "nonce" bạn sẽ dùng để đảm bảo rằng mã thông báo nhận dạng mà bạn nhận được đã được cấp riêng trong phản hồi 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 mã hoá bảo mật 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 trong câu trả lờ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ị được chuyển của 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. Khi bạn thiết lập FBSDKLoginButton, hãy đặt tính năng uỷ quyền thành nhận 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ỳ tên nào khác Các mô-đun Firebase mà người được uỷ quyề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 FirebaseApp thực thể dùng chung trong Phương thức 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. 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 nó đến cấu trúc App của bạn 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. Cho hãy xem hướng dẫn về SwiftUI để biết thêm thông tin.

    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 từ Facebook phản hồi 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à được liên kết với thông tin đăng nhập—tức là tên người dùng và mật khẩu, số điện thoại số hoặc thông tin của nhà cung cấp dịch vụ xác thực – người dùng đã đăng nhập. Thông tin mới này được lưu trữ như một phần của dự án Firebase và có thể được dùng để xác định một 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 ứng dụng của mình, bạn có thể lấy thông tin hồ sơ cơ bản của người dùng từ User . Xem phần Quản lý người dùng.

  • Trong Cơ sở dữ liệu theo thời gian thực của Firebase và Cloud Storage Quy tắc bảo mật, bạn có thể lấy mã nhận dạng người dùng duy nhất của người dùng đã đăng nhập từ biến auth, để kiểm soát loại 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 bằng nhiều phương thức 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 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ộ phạm vi xác thực . Hãy xem bài viết Xử lý lỗi.