在 iOS 上使用 Facebook 登录服务进行身份验证

您可以将 Facebook 登录机制集成到您的应用中,让您的用户能够使用自己的 Facebook 帐号进行 Firebase 身份验证。

准备工作

  1. 将 Firebase 添加到您的 iOS 项目。在您的 Podfile 中添加以下 Pod:
    pod 'Firebase/Auth'
    
  2. 如果您尚未将您的应用与 Firebase 项目相关联,请在 Firebase 控制台中进行关联。
  3. Facebook for Developers 网站上,为您的应用获取应用 ID应用密钥
  4. 启用 Facebook 登录机制:
    1. Firebase 控制台中,打开身份验证部分。
    2. 登录方法标签页上,启用 Facebook 登录方法,并指定您之前从 Facebook 获得的应用 ID应用密钥
    3. 然后,请务必转到 Facebook for Developers 网站,依次点击 Product Settings > Facebook Login 配置,然后在您的 Facebook 应用的设置页面中,确保您的 OAuth 重定向 URI(例如 my-app-12345.firebaseapp.com/__/auth/handler)出现在 OAuth redirect URIs 列表中。

进行 Firebase 身份验证

  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. UIApplicationDelegate 中导入 Firebase 模块:

    Swift

    import Firebase

    Objective-C

    @import Firebase;
  3. 配置一个 FirebaseApp 共享实例(通常在应用的 application:didFinishLaunchingWithOptions: 方法中配置):

    Swift

    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
  4. 用户成功登录后,您可在 didCompleteWithResult:error: 的实现代码中,为已登录的用户获取一个访问令牌,然后用该访问令牌换取 Firebase 凭据:

    Swift

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

    Objective-C

    FIRAuthCredential *credential = [FIRFacebookAuthProvider
        credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];
    
  5. 最后,使用 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 项目中,无论用户采用何种方式登录,您项目中的每个应用都可以使用此帐号来识别用户。

  • 在您的应用中,您可以从 FIRUser 对象中获取用户的基本个人资料信息。请参阅管理用户

  • 在您的 Firebase 实时数据库和 Cloud Storage 安全规则中,您可以从 auth 变量获取已登录用户的唯一用户 ID,然后利用此 ID 来控制用户可以访问哪些数据。

您可以通过将身份验证提供方凭据关联至现有用户帐号,让用户可以使用多个身份验证提供方登录您的应用。

如需让用户退出登录,请调用 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;
}

您可能还需要为所有身份验证错误添加错误处理代码。请参阅处理错误