Firebase Auth UI如何处理重新认证?

我正在为我的Swift iOS应用程序使用Firebase Auth。 Google建议使用Firebase Auth UI作为“drop in”身份validation系统,但它只处理初始登录。 我现在正在努力允许用户进行配置文件更改,例如电子邮件和密码。

用于进行这些更改的文档会在某些位置提及某些更改需要用户最近登录(请参阅https://firebase.google.com/docs/auth/ios/manage-users#get_the_currently_signed-in_user ):

某些安全敏感操作(例如删除帐户,设置主电子邮件地址和更改密码)要求用户最近登录。如果您执行其中一项操作,并且用户已在很久以前登录,则动作因FIRAuthErrorCodeCredentialTooOld错误而失败。

首先,API中的任何地方似乎都没有FIRAuthErrorCodeCredentialTooOld错误。

其次,文档建议使用reauthenticate(with:)来解决此问题,使用此代码示例:

 let user = FIRAuth.auth()?.currentUser var credential: FIRAuthCredential // Prompt the user to re-provide their sign-in credentials user?.reauthenticate(with: credential) { error in if let error = error { // An error happened. } else { // User re-authenticated. } } 

问题是,因为我使用了Firebase Auth UI,所以我没有用于获取用户凭据的自定义UI。

我目前的想法是,我可以通过在发生此错误时提供用于登录的相同Firebase Auth UI来重新进行身份validation。 但是,我不知道这是否是受制裁的方式,或者它是否会起作用,或者它是否会在将来继续发挥作用。 我检查了Firebase Auth UI代码库,并且在任何地方都没有调用reauthenticate() 。 该文档特别针对此错误调用此方法,所以我很困惑。

如果我需要构建一个完整的UI来执行重新认证,包括多个提供商,那么使用Firebase Auth UI有什么意义呢?

关于错误代码,文档只需要更新。 错误代码现在称为FIRAuthErrorCode.errorCodeRequiresRecentLogin

现在,从您面临的UI问题UIAlertController ,为什么不提供一个带有文本字段的UIAlertController ,用户可以使用该文本字段输入密码进行重新validation? 它肯定比创建整个视图控制器更简单(和用户友好)。

以下是一个非常简单的示例,说明如何重新validation用户身份而不会遇到太多麻烦:

 // initialize the UIAlertController for password confirmation let alert = UIAlertController(title: "", message: "Please, enter your password:", preferredStyle: UIAlertControllerStyle.alert) // add text field to the alert controller alert.addTextField(configurationHandler: { (textField) in textField.placeholder = "Password" textField.autocapitalizationType = .none textField.autocorrectionType = .no textField.isSecureTextEntry = true }) // delete button action alert.addAction(UIAlertAction(title: "Delete account", style: UIAlertActionStyle.destructive, handler: {action in // retrieve textfield let txtFld = alert.textFields![0] // init the credentials (assuming you're using email/password authentication let credential = FIREmailPasswordAuthProvider.credential(withEmail: (FIRAuth.auth()?.currentUser?.email)!, password: txtFld.text!) FIRAuth.auth()?.currentUser?.reauthenticate(with: credential, completion: { (error) in if error != nil { // handle error - incorrect password entered is a possibility return } // reauthentication succeeded! }) })) // cancel reauthentication alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: {action in })) // finally, present the alert controller self.present(alert, animated: true, completion: nil) 

每当您需要更改用户的电子邮件或删除其帐户(密码重置根本不需要登录)时,请使用上面的代码段弹出一个警报控制器,他们可以在那里重新输入密码。

编辑:请注意,上面提供的代码强制解包当前用户的电子邮件,因此请确保您在该阶段登录用户或您的应用程序将崩溃。