【问题标题】:How to change firebase email without reauthentication如何在不重新认证的情况下更改 Firebase 电子邮件
【发布时间】:2026-01-18 06:10:02
【问题描述】:

我在我的应用中实现了一个按钮,允许用户使用 Firebase 更改他们的电子邮件。

 @IBAction func resetEmail(_ sender: Any) {
        let alertController = UIAlertController(title: "Change Email", message: "", preferredStyle: .alert)
        alertController.addTextField { (textField : UITextField!) -> Void in
            textField.placeholder = "Enter New Email Address"

              let saveAction = UIAlertAction(title: "Save", style: .default, handler: { (action : UIAlertAction!) -> Void in

            //Reset Email

                let currentUser = Auth.auth().currentUser
            if Auth.auth().currentUser != nil{
                currentUser?.updateEmail(to: textField.text!) { error in
                    if let error = error {
                        print(error)
                    } else {
                        print("CHANGED")
                        let user = Auth.auth().currentUser
                        let name = user?.displayName!
                        let ref = Database.database().reference().child("main").child("users_sen").child(name!).child("email")
                        ref.setValue(textField.text!)

                    }
                }
            }

            })


        alertController.addAction(saveAction)
        }
        self.present(alertController, animated: true, completion: {
            alertController.view.superview?.isUserInteractionEnabled = true
            alertController.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.alertClose(gesture:))))

        })
    }

但是,当我运行它并尝试更改电子邮件时,它给了我这个错误:

UserInfo={NSLocalizedDescription=This operation is sensitive and requires 
recent authentication. Log in again before retrying this request.

并告诉我重新签名以更改电子邮件。我该如何避免这种情况?如何在不重新登录的情况下更改电子邮件?

这就是我更改密码的方式:

  // Password updated.
             let currentUser = Auth.auth().currentUser
            currentUser?.updatePassword(to: textField.text!) { error in
                if let error = error {

                } else {
                    // Password updated.
                    print("success")

                }
            }

            let userEmail = Auth.auth().currentUser?.email
            self.currentPassword = textField.text!

            let credential = EmailAuthProvider.credential(withEmail: userEmail!, password: textField.text!)

            currentUser?.reauthenticate(with: credential) { error in
                if let error = error {
                    // An error happened.
                } else {
                    // User re-authenticated.
                }
            }

【问题讨论】:

    标签: ios swift firebase firebase-authentication


    【解决方案1】:

    基于 Firebase 的documentation,您需要在执行此类操作时重新对用户进行身份验证。

    重新验证用户身份 一些对安全敏感的操作,例如 删除帐户、设置主电子邮件地址和更改 密码—要求用户最近登录。如果您执行 这些操作之一,并且用户登录时间过长,该操作 失败并出现错误。发生这种情况时,请通过以下方式重新验证用户身份 从用户那里获取新的登录凭据并传递 凭据以 reauthenticateWithCredential。

    let user = Auth.auth().currentUser
    let credential = EmailAuthProvider.credential(withEmail: "email", password: "password")
    
    user?.reauthenticate(with: credential)
    { error in
       if let error = error {
          // An error happened.
       } else {
          // User re-authenticated.
          user?.updateEmail(to: "newemail")
          { error in
    
          }
       }
    }   
    

    【讨论】:

    • 几乎每一行都给我一个错误是swift 4吗?
    • 我只想更改电子邮件。是否可以在不更新密码的情况下做到这一点
    • 我上面贴的代码不会改变密码,只是邮箱。但是在更改电子邮件等属性时需要重新验证,因此需要再次输入密码,或者如果您的应用程序中已经有密码,则只需通过
    • 我使用相同的重新身份验证来更改用户的密码。但是我输入了当前的电子邮件,因为 firebase 有这个选项,但是我很难更改电子邮件,因为 firebase 没有提供 firebase 当前密码。我更新了我的问题以显示我如何更新密码。
    【解决方案2】:

    要在不重新验证的情况下更改用户电子邮件,您还可以利用 Cloud Functions。一个示例行动方案可能是:

    1. 创建一个接受用户访问令牌和新电子邮件地址作为参数的函数
    2. 在函数中,验证访问令牌并从中获取用户 ID
    3. 在函数中,调用 admin.auth().updateUser(userId, { email: newEmail })
    4. 从客户端调用新函数

    注意:此解决方案的安全性较低,因为用户意图未通过附加身份验证进行验证。因此,任何掌握用户设备的人都可以更改他们的电子邮件地址。

    【讨论】:

    • 这是不正确的。根据文档:当检测到用户的主要帐户更改时,刷新令牌过期。这包括密码或电子邮件地址更新等事件。你用什么来做这件事并不重要,谷歌云功能,你自己的后端,或者其他什么。 firebase.google.com/docs/auth/admin/manage-sessions
    【解决方案3】:

    如果您使用电子邮件和密码来验证用户身份,您应该这样做。

    1. 您必须使用凭据重新对用户进行身份验证
    2. 重新验证用户身份
    3. 更新电子邮件

    在此之前不要忘记获取班级中的当前用户并像这样导入 Firebase:

    ...
    import Firebase
    class Blabla {
    ...
    var currentUser: User? {
       return Auth.auth().currentUser
     }
    

    然后:

    
    func updateUserEmail(newEmail: String, password: String) {
    
    // 1. Get the credential
    guard let currentEmail = currentUser?.email else {return}
     var credential = EmailAuthProvider.credential(withEmail: currentEmail, password: password)
    

    您无法直接获得password,因此您必须通过文本字段或其他方式向用户询问其密码。

    // 2. Re-authenticate the user 
    //(To change mail or password, the user must to be authentificate a short time ago !!!)
    
        self.currentUser?.reauthenticate(with: credential, completion: { (result, error) in
                if error != nil {
                    print("ERROR: ", error?.localizedDescription)
                    return
                }
    
                 //3. Update email
                 self.currentUser?.updateEmail(to: newEmail, completion: { (error) in
                    if error != nil {
                        print("ERROR: ", error?.localizedDescription)
    
                    }else {
                        //Do something, for example present an alert of confirmation..
                    }
                })
            })
    

    步骤 1 中同一函数中的所有代码。

    【讨论】:

      最近更新 更多