【发布时间】:2018-09-12 10:34:43
【问题描述】:
我想在 Flutter 中使用 Firebase 更改当前用户密码。 任何人都可以帮助我如何实现更改密码方法?
【问题讨论】:
标签: firebase dart firebase-authentication flutter
我想在 Flutter 中使用 Firebase 更改当前用户密码。 任何人都可以帮助我如何实现更改密码方法?
【问题讨论】:
标签: firebase dart firebase-authentication flutter
我知道这是一个迟到的帖子,但现在可以更改登录用户的密码。请务必通知用户重新登录,因为这是一项敏感操作。
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.
});
}
【讨论】:
如果您在 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) {
});}
【讨论】:
这应该根据最新版本的 firebase 工作:
final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
User currentUser = firebaseAuth.currentUser;
currentUser.updatePassword("newpassword").then((){
// Password has been updated.
}).catchError((err){
// An error has occured.
})
【讨论】:
目前不支持此功能。
当这个拉取请求被合并https://github.com/flutter/plugins/pull/678 时,Flutter firebase_auth 包将支持它。
【讨论】:
正如@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密钥
【讨论】: