React Native - Firebase auth persistence not working

可紊 提交于 2019-12-30 00:38:07

问题


Firebase auth does not persist logged in user and everytime I refresh or reopen app I have to sign in again.

I have tried setting persistence to local and the callback does verify its set but the persistence is still no working

For setting persistence I am using...

  //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)
  });

. . . For signing in I am using this code

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)
      // ...
    });

And here is the code I am using to check login status...

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');
      }

if there anything I am not doing right


回答1:


You don't need to set persistence. Firebase handles it for you by default. You just need to call this function to check whether user is logged or not:

firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        console.log('user is logged');
      }
}

This will not be triggered only if user has sign out or cleaned app data.

You can find more details in the official docs: https://firebase.google.com/docs/auth/web/manage-users

Hope it helps.




回答2:


Make sure you do not restrict the 'Token Service API' in the console, with the API key you are using. I did not add the service to my key, and it logged me out every 3-4 hours, even with the right code suggested above.



来源:https://stackoverflow.com/questions/46143273/react-native-firebase-auth-persistence-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!