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

时间:2018-09-12 10:34:44

标签: firebase dart firebase-authentication flutter

我想使用Flutter中的Firebase更改当前用户密码。 有人可以帮我实现更改密码的方法吗?

5 个答案:

答案 0 :(得分:1)

当前不支持此功能。

当合并此拉取请求https://github.com/flutter/plugins/pull/678时,Flutter firebase_auth软件包将支持该请求。

答案 1 :(得分:1)

@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'},  
  )
}

您可以在getIdToken()对象上使用FirebaseUser方法来获得idToken

您可以在控制台的项目设置下获取firebase api密钥

enter image description here

答案 2 :(得分:0)

我知道这是最新的帖子,但是现在可以更改已登录用户的密码。请确保通知用户再次登录,因为这是一项敏感操作。

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("Succesfull 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.
    });
  }

答案 3 :(得分:0)

这应该根据最新版本的firebase起作用:
final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
User currentUser = firebaseAuth.currentUser;
currentUser.updatePassword("newpassword").then((){}).catchError((err){})

答案 4 :(得分:0)

如果您在 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) {
 
});}