Firebase身份验证不会保留登录用户,每次刷新或重新打开应用时,我都必须重新登录。
我已经尝试将持久性设置为本地,并且回调确实验证了它的设置但是持久性仍然无法正常工作
设置持久性我正在使用...
//set auth persistence
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
.then(function() {
console.log("successfully set the persistence");
})
.catch(function(error){
console.log("failed to ser persistence: " + error.message)
});
。 。 。 登录时我正在使用此代码
firebase.auth().signInWithEmailAndPassword(email, password)
.then((user) =>{
this.checkAccountStatus(user.uid, user.email);
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorMessage)
// ...
});
这是我用来检查登录状态的代码......
if (firebase.auth().currentUser) {
const currentUser = firebase.auth().currentUser;
console.log("Signed in username" + currentUser.displayName);
this.props.navigation.navigate('AppTab');
}else{
console.log("no user signed in");
this.props.navigation.navigate('AuthTab');
}
如果有什么我做得不对
答案 0 :(得分:15)
您不需要设置持久性。 Firebase默认为您处理。您只需要调用此函数来检查用户是否已记录:
token base authentication
仅当用户退出或清除应用数据时才会触发此操作。
您可以在官方文档中找到更多详细信息:https://firebase.google.com/docs/auth/web/manage-users
希望它有所帮助。
答案 1 :(得分:1)
请确保您使用的API密钥不限制console中的“令牌服务API”。我没有将服务添加到密钥中,即使使用上面建议的正确代码,它也每3-4小时使我注销一次。
答案 2 :(得分:1)
Firebase
现在建议使用firestore
代替realtime-database
,并且默认情况下它管理脱机持久性。在其文档here
您只需要通过以下代码访问用户:
if (auth().currentUser !== null) {
console.log('User is logged in');
console.log(auth().currentUser.email);
props.navigation.navigate('Home');
} else {
props.navigation.navigate('Login');
}
即使用户关闭应用程序,此代码也将引导您进入主屏幕。要清除用户的凭据,您需要使用此代码手动注销用户。
try {
auth()
.signOut()
.then(props.navigation.navigate('Login'));
} catch (error) {
Alert.alert('Error', error.toString());
}
您还可以检查this简单应用(已在其中使用react hooks
)以获取更多帮助。