When to set Firebase auth state persistence

社会主义新天地 提交于 2020-08-07 08:19:44

问题


according to the guide, the firebase auth state persistance is set before the actual login method is called:

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
  .then(function() {
    // Existing and future Auth states are now persisted in the current
    // session only. Closing the window would clear any existing state even
    // if a user forgets to sign out.
    // ...
    // New sign-in will be persisted with session persistence.
    return firebase.auth().signInWithEmailAndPassword(email, password);
  })
  .catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });

See https://firebase.google.com/docs/auth/web/auth-state-persistence

However, shouldn't it be the other way around? Shouldn't I first ensure that the login was successful and then attempt to set the persistence?

In the suggested approach, a user could have like 10 wrong login attempts, and everytime he would request firebase to set the persistence, even if the login was not successful.

It would be the same for Signup for instance. Is there an actual way to set the firebase auth persistance persistantly to SESSION or NONE by default?


回答1:


Actually, it is quite flexible. You can set it once and the last setting will always be applied. You don't need to that each time. It will remember the last persistence setting as long as you don't reload the page.

Also you have the ability to change the persistence after sign in. So if the user signs in and the default persistence was used and then you set persistence to SESSION, the user state will be converted to SESSION.




回答2:


In my projects I set/reset it in the onAuthStateChanged listener. Something like the following:

firebase.auth.onAuthStateChanged(authUser => {
  authUser
    ? localStorage.setItem('authUser', JSON.stringify(authUser))
    : localStorage.removeItem('authUser')
});

You can read more about it over here.



来源:https://stackoverflow.com/questions/50457810/when-to-set-firebase-auth-state-persistence

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