Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Authentication not persisting

Authentication doesn't seem to persist after page has been refreshed. Even after using firebase.auth.Auth.Persistence.LOCAL.

Whenever I log into my app, it successfully redirects me to the Dashboard. But, when page has been refreshed, accessing Dashboard is not possible.

Here's my code.

Filename: login.component.ts

import { Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';

import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Observable';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFirestore } from 'angularfire2/firestore';

@Component({
    ...
})
export class LoginComponent implements OnInit {

    email: string = '';
    password: string = '';

    constructor(public afAuth: AngularFireAuth, private router: Router, private fb: FormBuilder) {}

    signIn(credentials) {
        this.email = credentials.email;
        this.password = credentials.password;

        this.afAuth.auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL).then(() => {
            this.afAuth.auth.signInWithEmailAndPassword(this.email, this.password).then(() => {
                this.router.navigate(['dashboard']);
            }).catch((err) => {
                ...
            })
        }).catch((err) => {
            ...
        })
    }

    ngOnInit() {}

}

Filename: auth.guard.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';

import { AngularFireAuth } from 'angularfire2/auth';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router, private afAuth: AngularFireAuth) {}

    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        var authed = this.afAuth.auth.currentUser;

        if (authed) {
            return true;
        } else {
            this.router.navigate(['/']);
            return false;
        }
    }
}

Additional Info:

@angular/animations: 5.0.0
@angular/common: 5.0.0
@angular/compiler: 5.0.0
@angular/core: 5.0.0
@angular/forms: 5.0.0
@angular/http: 5.0.0
@angular/platform-browser: 5.0.0
@angular/platform-browser-dynamic: 5.0.0
@angular/router: 5.0.0
angular2-materialize: 15.1.10
angularfire2: 5.0.0-rc.3
core-js: 2.4.1
firebase: 4.6.1
hammerjs: 2.0.8
jquery: 2.2.4
materialize-css: 0.100.2
rxjs: 5.5.2
zone.js: 0.8.14

Expected Result:

http://localhost:4200/dashboard (ACCESSIBLE WHILE LOGGED IN)

Current Result:

http://localhost:4200/dashboard (INACCESSIBLE WHILE LOGGED IN; REDIRECTS TO HOME)

Where did I go wrong or something else?

like image 897
Etosticity Avatar asked Nov 06 '17 10:11

Etosticity


People also ask

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.

Is Firebase persistent?

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.

Can I use Firebase just for authentication?

You can use Firebase Authentication to allow users to sign in to your app using one or more sign-in methods, including email address and password sign-in, and federated identity providers such as Google Sign-in and Facebook Login.

How does Firebase handle authentication?

Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more.


1 Answers

You need to use onAuthStateChanged listener to detect the initial auth state:

firebase.auth().onAuthStateChanged(user => {
  if (user) {
    // User is signed in.
  } else {
    // User is signed out.
  }
});
like image 110
bojeil Avatar answered Sep 23 '22 09:09

bojeil