Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2+ Firebase Authentication - Set Login State Persistence

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've seen that firebase is supposed to have state persistence by default, but current logins in the app only last until the page is refreshed, after which login is required again, which doesn't seem right.

I know that I have to use the statePersistence method, as shown in the documentation, but this doesn't make it clear as to how this is actually implemented into a login/auth service in angular 2+ apps.

How to I implement session statePersistence into the following authentication service?:

auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import * as firebase from 'firebase/app';
import { AngularFireAuth } from 'angularfire2/auth';

@Injectable()

export class AuthService {

  private user: Observable<firebase.User>;

  isAuthenticated: boolean = false;

  constructor(private firebaseAuth: AngularFireAuth, private router: Router) {
    this.user = firebaseAuth.authState;
  }

  signIn(email: string, password: string) {
    this.firebaseAuth
        .auth
        .signInWithEmailAndPassword(email, password)
        .then(value => {
            console.log('Signed In');
            this.isAuthenticated = true;
            this.router.navigateByUrl('/dashboard');
        })
        .catch(err => {
            console.log('Sign-In Error: ', err.message);
        });
  }

  signInGoogle() {
    return this.firebaseAuth.auth.signInWithPopup(
        new firebase.auth.GoogleAuthProvider()
    )
  }
like image 381
nick.cook Avatar asked Feb 06 '18 15:02

nick.cook


People also ask

Does Firebase authenticate persist?

Note that Firebase Auth web sessions are single host origin and will be persisted for a single domain only. Indicates that the state will only persist in the current session or tab, and will be cleared when the tab or window in which the user authenticated is closed.

How long does Firebase auth session last?

By default, a session ends (times out) after 30 minutes of user inactivity. There is no limit to how long a session can last.

Does Firebase auth token expire?

At a minimum, you need to provide a uid , which can be any string but should uniquely identify the user or device you are authenticating. These tokens expire after one hour.


1 Answers

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);
  });
}
like image 86
Jack Avatar answered Oct 04 '22 01:10

Jack