Firebase 身份验证 UI 如何处理重新身份验证?

And*_*hou 6 ios firebase swift firebase-authentication firebaseui

我正在为我的 Swift iOS 应用程序使用 Firebase Auth。Google 建议使用 Firebase Auth UI 作为“插入式”身份验证系统,但它仅处理初始登录。我现在正致力于允许用户更改配置文件,例如电子邮件和密码。

进行这些更改的文档在多个地方提到某些更改要求用户最近登录(请参阅https://firebase.google.com/docs/auth/ios/manage-users#get_the_currently_signed-in_user):

某些安全敏感操作(例如删除帐户、设置主电子邮件地址和更改密码)要求用户最近登录。如果您执行这些操作之一,而用户登录时间过长,则操作因 FIRAuthErrorCodeCredentialTooOld 错误而失败。

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

其次,文档建议使用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.
  }
}
Run Code Online (Sandbox Code Playgroud)

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

我目前的想法是,我可以通过在发生此错误时提供用于登录的相同 Firebase 身份验证 UI 来重新进行身份验证。但是,我不知道这是否是执行此操作的认可方式,或者它是否会起作用,或者将来是否会继续起作用。我检查了 Firebase Auth UI 代码库,没有reauthenticate()任何地方可以调用。文档在出现此错误的情况下专门调用此方法做了大量工作,所以我很困惑。

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

Thu*_*uct 1

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

现在,就您面临的 UI 问题而言,为什么不直接提供一个UIAlertController文本字段,用户可以使用该文本字段输入密码以进行重新身份验证?它肯定比创建整个视图控制器简单得多(并且用户友好)。

以下是一个非常简单的示例,说明如何重新验证用户身份而无需经历这么多麻烦:

// 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)
Run Code Online (Sandbox Code Playgroud)

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

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