dart 如何在Flutter中使用Firebase更改密码

7rfyedvj  于 2023-11-14  发布在  Flutter
关注(0)|答案(8)|浏览(127)

我想在Flutter中使用Firebase更改当前用户密码。谁能帮助我实现更改密码的方法?

fnvucqvd

fnvucqvd1#

我知道这是一个迟来的帖子,但现在可以更改登录用户的密码。请确保通知用户重新登录,因为这是一个敏感的操作。

void _changePassword(String password) async{
   //Create an instance of the current user. 
    FirebaseUser user = await FirebaseAuth.instance.currentUser();
   
    //Pass in the password to updatePassword.
    user.updatePassword(password).then((_){
      print("Successfully changed password");
    }).catchError((error){
      print("Password can't be changed" + error.toString());
      //This might happen, when the wrong password is in, the user isn't found, or if the user hasn't logged in recently.
    });
  }

字符串

e7arh2l6

e7arh2l62#

如果你在这里的解决方案在2021年,并获得重新认证错误->

void _changePassword(String currentPassword, String newPassword) async {
final user = await FirebaseAuth.instance.currentUser;
final cred = EmailAuthProvider.credential(
    email: user.email, password: currentPassword);

user.reauthenticateWithCredential(cred).then((value) {
  user.updatePassword(newPassword).then((_) {
    //Success, do something
  }).catchError((error) {
    //Error, show something
  });
}).catchError((err) {
 
});}

字符串

ne5o7dgx

ne5o7dgx3#

这应该根据最新版本的firebase工作:

final FirebaseAuth firebaseAuth = FirebaseAuth.instance;  
User currentUser = firebaseAuth.currentUser; 
currentUser.updatePassword("newpassword").then((){
  // Password has been updated.
}).catchError((err){
  // An error has occured.
})

字符串

2admgd59

2admgd594#

目前不支持此功能。
当这个pull请求被合并https://github.com/flutter/plugins/pull/678时,Flutter firebase_auth包将支持它。

rjzwgtxy

rjzwgtxy5#

由于**@Gunter**提到该功能目前还无法使用,您可以暂时使用firebase REST API的方式更改密码。

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';

Future<Null> changePassword(String newPassword) async {
  const String API_KEY = 'YOUR_API_KEY';
  final String changePasswordUrl =
      'https://www.googleapis.com/identitytoolkit/v3/relyingparty/setAccountInfo?key=$API_KEY';

      final String idToken = await user.getIdToken(); // where user is FirebaseUser user

    final Map<String, dynamic> payload = {
      'email': idToken,
      'password': newPassword,
      'returnSecureToken': true
    };

  await http.post(changePasswordUrl, 
    body: json.encode(payload), 
    headers: {'Content-Type': 'application/json'},  
  )
}

字符串
可以通过对FirebaseUser对象使用getIdToken()方法来获取idToken
您可以在控制台的项目设置下获取firebase API密钥
x1c 0d1x的数据

wz1wpwve

wz1wpwve6#

以下是在Firebase Futter 2022中更改密码的最新方法

Future<bool> _changePassword(String currentPassword, String newPassword) async {
    bool success = false;

    //Create an instance of the current user.
    var user = await FirebaseAuth.instance.currentUser!;
    //Must re-authenticate user before updating the password. Otherwise it may fail or user get signed out.

    final cred = await EmailAuthProvider.credential(email: user.email!, password: currentPassword);
    await user.reauthenticateWithCredential(cred).then((value) async {
      await user.updatePassword(newPassword).then((_) {
        success = true;
        usersRef.doc(uid).update({"password": newPassword});
      }).catchError((error) {
        print(error);
      });
    }).catchError((err) {
      print(err);
    });

    return success;
  }

字符串

a1o7rhls

a1o7rhls7#

在**@Deepanshu Chowdhary**的答案的基础上,增加了一点错误处理和一些null安全性(在我的用例中,我可以假设当我运行这个函数时,用户和电子邮件都不是null,但你可能需要先检查一下)。
如果一切顺利,函数将返回null,否则它将返回指定错误代码的特定字符串或只是“未知”。

static Future<String?> changePassword(String oldPassword, String newPassword) async {
    User user = FirebaseAuth.instance.currentUser!;
    AuthCredential credential = EmailAuthProvider.credential(email: user.email!, password: oldPassword);

    Map<String, String?> codeResponses = {
      // Re-auth responses
      "user-mismatch": null,
      "user-not-found": null,
      "invalid-credential": null,
      "invalid-email": null,
      "wrong-password": null,
      "invalid-verification-code": null,
      "invalid-verification-id": null,
      // Update password error codes
      "weak-password": null,
      "requires-recent-login": null
    };

    try {
      await user.reauthenticateWithCredential(credential);
      await user.updatePassword(newPassword);
      return null;
    } on FirebaseAuthException catch (error) {
      return codeResponses[error.code] ?? "Unknown";
    }
  }

字符串

ioekq8ef

ioekq8ef8#

2023 solution flutter_doc

//change password
  Future<void> changePassword(String newPassword) async {
    final user = FirebaseAuth.instance.currentUser;

    if (user != null) {

      debugPrint('password has been changed');
      await user.updatePassword(newPassword);
    } else {
      debugPrint("password hasnt been changed");
      // No user is signed in.
    }
  }

字符串

相关问题