Firebase Authentication in Angular 8 with AngularFire2

Article By Digamber Rawat Published on
Firebase Authentication in Angular 8 with AngularFire2 tutorial will be the most popular topic nowadays. Firebase is a real-time NoSQL database to create modern web and mobile application. Setting up an authentication system with Firebase in your web and mobile apps is very easy.

In this tutorial, we’ll cover up following Firebase authentication system topics:

DigitalOcean Affiliate
  • signInWithEmailAndPassword
  • email/password signup

Install & Configure AngularFire2 Library in Angular 8

In our first step, we’ll set up the Firebase authentication project using Angular CLI. To activate the Firebase Authentication service, go inside your Firebase admin area and enable the Email/Password sign-in option inside the Authentication section.

If you are absolute begginer in Firebase then you must go through this tutorial: Set up Firebase Account | Setup AngularFire2 Library in Angular 8

Now, we’ll run the below command in the terminal to install AngularFire2 library from Node Package Manager. This command includes the Firebase SDK inside your project.

npm install firebase @angular/fire --save

It’s time to make the connection between your Angular app and the Firebase database. Go to your Firebase console, add the new project and get your Firebase project credentials and include in the environment files in your project.

src > environments > environment.ts

export const environment = {
  production: false,
  firebaseConfig: {
    apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    authDomain: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    databaseURL: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    projectId: "xxxxxxxxxxxxx",
    storageBucket: "xxxxxxxxxxxxxxx",
    messagingSenderId: "xxxxxxxxxxxxxx",
    appId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  }
};

In next step we will import AngularFire2 services e.g AngularFireModule, AngularFireAuthModule and enviorment variable in app module file.

src > app > app.module.ts

/* Firebase services */
import { AngularFireModule } from "@angular/fire";
import { AngularFireAuthModule } from "@angular/fire/auth";
import { environment } from '../environments/environment';
/* Auth service */
import { AuthenticationService } from './shared/authentication.service';
@NgModule({
declarations: [...],
imports: [
AngularFireAuthModule,
AngularFireModule.initializeApp(environment.firebaseConfig),
],
providers: [AuthenticationService],
bootstrap: [...],
schemas: [...]
})
export class AppModule { }

Build Angular 8 Service to Configure Firebase Authentication Service

Now, we are going to work on the essential part of this tutorial, which is writing the logic for enabling sign in, sign up or sign out a user from the Angular 8 Firebase authentication app. For the better project manageability, we’ll create a separate folder by the name of shared in which we’ll keep our AuthenticationService file and write authentication methods in it.

Run the command in Angular CLI to generate authentication service file without spec.ts file:

ng g s shared/Authentication --spec=false

Now here we have the full Firebase authentication (AuthenticationService) using AngularFireAuth:

src > app > share > authentication.service.ts

import { Injectable } from '@angular/core';
import { AngularFireAuth } from "@angular/fire/auth";
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
userData: Observable<firebase.User>;
constructor(private angularFireAuth: AngularFireAuth) {
this.userData = angularFireAuth.authState;
}
/* Sign up */
SignUp(email: string, password: string) {
this.angularFireAuth
.auth
.createUserWithEmailAndPassword(email, password)
.then(res => {
console.log('Successfully signed up!', res);
})
.catch(error => {
console.log('Something is wrong:', error.message);
});    
}
/* Sign in */
SignIn(email: string, password: string) {
this.angularFireAuth
.auth
.signInWithEmailAndPassword(email, password)
.then(res => {
console.log('Successfully signed in!');
})
.catch(err => {
console.log('Something is wrong:',err.message);
});
}
/* Sign out */
SignOut() {
this.angularFireAuth
.auth
.signOut();
}  
}

Here comes the exciting thing as you can see angularFireAuth.auth is returning promisies. Now we have to focus on 2 responses: then and catch, these methods return the success and error state individually.

Firebase allows creating the authentication service very quickly with Google, Facebook, Twitter and GitHub. In this Angular 8 Firebase authentication tutorial we are using signInWithEmailAndPassword, createUserWithEmailAndPassword and signOut methods.

Implement Firebase Authentication Sign in, Sign up and Sign out in Angular 8 Component

In this final part of this Firebase authentication tutorial, we are going to consume the Angular 8 authentication service. We’ll import the auth service in component and create the signup, sign in and sign out functionality.

src > app > app.component.ts

import { Component } from '@angular/core';
import { AuthenticationService } from './shared/authentication.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
email: string;
password: string;
constructor(public authenticationService: AuthenticationService) {}
signUp() {
this.authenticationService.SignUp(this.email, this.password);
this.email = ''; 
this.password = '';
}
signIn() {
this.email = ''; 
this.password = '';
}
signOut() {
this.authenticationService.SignOut();
}
}

Firstly, we’ll start by injecting the Angular Firebase authentication service in the constructor method of the AppComponent class. Then we’ll declare the authentication methods, and these methods will call the auth service APIs. We’ll use public keyword with Authentication Service in the constructor rather than private keyword because we needed to access the Angular authentication service directly from the Angular 8 component.

In the Angular component, we are using the async pipe to determine the logged-in state of the user.
src > app > app.component.html

<h1 *ngIf="authenticationService.userData | async">Hello {{ (authenticationService.userData | async)?.email }}</h1>
<div *ngIf="!(authenticationService.userData | async)">
<input type="text" [(ngModel)]="email" placeholder="email">
<input type="password" [(ngModel)]="password" placeholder="password">
<button (click)="signUp()">Sign Up</button>
<button (click)="signIn()">Login</button>
</div>
<button (click)="signOut()" *ngIf="authenticationService.userData | async">Logout</button>

Finally we’ve completed Angular 8 Firebase Authentication tutorial, i hope this tutorial will help you understand the basics of how to use AngularFire2 library to build authentication system in Angular 8.

If you loved this tutorial then don’t forget to share it with others, you can found GitHub repo here for this project.

Digamber Rawat
Digamber Rawat

I am a software engineer from India, love to learn and write about latest web and mobile technologies like: MongoDB, Angular 2+, Firebase, Express JS, Python, Node JS, JavaScript, RxJS etc.