Authentication with AngularFire 6

Angular + Firebase = AngularFire

It took me a long while to figure out the authentication with persistence in AngularFire 6 because of the lack of examples and information on the same, so that I thought I’d contribute to help the next person figuring it out.

You can find my code repository and my auth service code file on GitHub.
Now, Let’s get started.

1. Install AngularFire & Create Service

ng add @angular/fire
ng service auth
ng component test

2. Adding FireAuth Module in Imports

// app.module.ts
import your_firebase_config from '../environments/production';
import { AngularFireModule } from '@angular/fire';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { AngularFireAuthGuardModule } from '@angular/fire/auth-guard';
@NgModule({
...
imports: [
AngularFireModule.initializeApp(your_firebase_config),
AngularFireAuthModule,
AngularFireAuthGuardModule
],
...
})

3. Login & Logout Actions

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import firebase from 'firebase/app';
@Injectable({ providedIn: 'root' })
export class AuthService {
constructor(private auth: AngularFireAuth) { }
loginBegin() {
// Our login provider here would be google
const providerObject = 'Google';
this.auth.setPersistence('local').then(() => {
this.auth.signInWithPopup(providerObject)
.then(() => this.isLoggedIn())
.catch(error => console.error(error.code));
});
}
}

Note the setPersistence('local') , this ensures the user authentication information is stored in your Indexed DB and can be used again later. i.e user is not forgotten when the tab is closed.

The this.isLoggedIn() function is called on successful login to update the login state.

import { BehaviorSubject } from 'rxjs';
public loggedInUser: BehaviorSubject<string>;
async isLoggedIn() {
const user = await this.auth.authState.pipe(first())
.toPromise();
if (user) {
// You have user information, update subscribers.
this.loggedInUser.next(true);
} else {
// User has logged out, update subscribers.
this.loggedInUser.next(user.email);
}
}

Here, this.loggedInUser is a class member that will update all the subscribing components when it’s value is modified.

import { BehaviorSubject } from 'rxjs';
public loggedInUser: BehaviorSubject<string>;

Let’s now create a simple logout function.

logoutBegin(reload = true) {
this.auth.signOut();
this.isLoggedIn();
}

this.auth.signOut() will remove all the information from IndexDB then will will update all the subscribers in this.isLoggedIn() functions.

3. Consuming the subscriber

export class TestComponent implements OnInit {
public isUserEmail = false;
constructor(private auth: AuthService) { }

ngOnInit() {
this.auth.loggedInUser
.subscribe(email => this.isUserEmail = email);
this.auth.isLoggedIn();
}
beginLogin() {
this.auth.loginBegin();
}
beginLogout() {
this.auth.logoutBegin();
}
}

There in the ngOnInit we first create a subscriber to update this.isUserEmail every time in it is changed. This variable now be used directly in the HTML files to reflect the values as and when they change.

Then we have the beginLogin() & beginLogout() . These can be invoked on the click of a button to login and logout the user.

That’s it, We have a working instance of AngularFire authentication with Persistence! Please checkout the code for a working example and let me know if I can improve this blog to make it even easier for folks new with AngularFire.

Hope this helped you to implement your authentication using AngularFire. Good luck with your project!

Stoic. Existentialist. Optimistically Nihilist. Snowdenist. Friendly. Confident. Perfectionist. Creative. Playful. Programmer. Philosopher.