Angular 2+ Firebase Authentication - Set Login State Persistence

后端 未结 3 1015
清酒与你
清酒与你 2021-01-12 14:07

I\'ve set up authentication using firebase for an angular app in an auth service, and I\'m trying to ensure session state persistence following successful login.

I\'

相关标签:
3条回答
  • 2021-01-12 14:38

    You're importing the entire firebase module. Only import auth. The following works for me:

    // Don't import the whole module, only `auth`.
    import { auth } from 'firebase/app';
    
    constructor(private readonly afAuth: AngularFireAuth) { }
    
    signIn() {
      this.afAuth.auth.setPersistence(auth.Auth.Persistence.LOCAL).then(() => {
        // Now sign-in using your chosen method.
        return this.afAuth.auth.signInAnonymously();
      }).catch((error) => {
        // Handle errors here.
        let errorCode = error.code;
        let errorMessage = error.message;
        console.error(errorCode, errorMessage);
      });
    }
    
    0 讨论(0)
  • 2021-01-12 14:46

    add

    this.firebaseAuth
        .auth
    
        .setPersistence(firebase.auth.Auth.Persistence.LOCAL)
    
        .signInWithEmailAndPassword(email, password)
    
    0 讨论(0)
  • 2021-01-12 15:01

    It is likely you are not using onAuthStateChanged listener to detect the initial Auth state on page load.

    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        // User signed in.
      } else {
        // User not signed in.
      }
    });
    
    0 讨论(0)
提交回复
热议问题