How to add Firebase Authentication to PWA or Angular project using AngularFire.


5 min read
How to add Firebase Authentication to PWA or Angular project using AngularFire.

Learn to implement Signup/Login in your PWA (Progressive Web Apps) or Angular App using Firebase Authentication services - which supports authentication using password, phone, other providers like Google, Facebook, Twitter, and more.

Good to know about AngularFireAuth:
We will use AngularFireAuth for authentication – AngularFireAuth is an library of AngularFire, which is officially supported AngularJS binding for Firebase.

AngularFireAuth.user provides us an Observable<User|null> to monitor our application's authentication State.

AngularFireAuth.auth returns an initialized firebase.auth.Auth instance, allowing us to log users in, out, etc. See the Firebase docs for more information on what methods are available.


If you already have your project it's good. If not, please follow the link.
Click here👆 to create your new PWA/Angular project.


In first step we will add Firebase to an Angular project.
Then enable the Email/Password sign-in method.
Follow me while I’ll show you how we can do that..

#1 Adding Firebase to an Angular project.

Before start, we need to set up Firebase configuration in our project by adding Firebase. Follow the link to add Firebase — Click here 👇👇

How to add Firebase to PWA or Angular project using AngularFire.
Setting up Firebase configuration in Ionic/Angular projects using AngularFire. AngularFire is the official library that connects Angular to Firebase. &gt; First of all, we will need to create a Firebase project. We have already done this when we deployed our PWA app to firebase [https://medium.com/@AnkitMaheshwariIn/build-a-progressive-web-app-pwa-with-ionic-4-ionic-framework-and-firebase-48183519c01…
Follow #2 After adding Firebase/AngularFire to your project.

#2 Enable the Email/Password sign-in method under the Authentication section of the Firebase console.

Click here to open Firebase console Then under your Firebase project click over Authentication Then click over Sign-in method Then under Sign-in providers enable Email/Password status.

Next… we’ll configure our app module with AngularFireAuthModule module. Let's finish this by importing the corresponding AngularFire modules (AngularFireAuthModule) in our app.module.ts file:

(Also notice that we’re importing and providing an AuthService. We’ll create that service next. We also need to import FormsModule to use ngModel directive, we'll use that later in this article.)

import { AngularFireModule } from '@angular/fire';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { FormsModule } from '@angular/forms';
import { AuthService } from './auth.service';
...
imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireAuthModule,
    FormsModule
  ],
providers: [
    ...
    AuthService
],
...

#3 Creating the Auth Service.

Our service will be a central place that allows us to login, signup or logout users, so we’ll define methods for these 3 actions. All the authentication logic will be in the AuthService, which will allow us to create components that doesn’t need to implement any auth logic and will help keep our components simple.

We can create the skeleton for the service using the Angular CLI, run this command:

ng g s service/auth

( g → generate, s → service, auth → service-name, service/auth means this will create AuthService into service folder )

Open-up your src/app/service/auth.service.ts file and add this code:

// auth.service.ts
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  user: Observable<firebase.User>;

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

  signup(email: string, password: string) {
    this.firebaseAuth
      .auth
      .createUserWithEmailAndPassword(email, password)
      .then(value => {
        console.log('Success!', value);
      })
      .catch(err => {
        console.log('Something went wrong:',err.message);
      });
  }

  login(email: string, password: string) {
    this.firebaseAuth
      .auth
      .signInWithEmailAndPassword(email, password)
      .then(value => {
        console.log('Nice, it worked!');
      })
      .catch(err => {
        console.log('Something went wrong:',err.message);
      });
  }

  logout() {
    this.firebaseAuth
      .auth
      .signOut();
  }
}

You’ll notice that the methods available on AngularFireAuth.auth (line no. 18, 30 of auth.service.ts) all return promises so we can use then and catch to deal with the success and error states respectively.

We use createUserWithEmailAndPassword (line no. 18 of auth.service.ts) and signInWithEmailAndPassword (line no. 30 of auth.service.ts) here we’re setting up email/password authentication — equivalent methods are also available for authentication with Twitter, Facebook and Google.

#4 Component Class and Template.

Now we have our auth service ready, it’s really simple to create a component that allow us for logging in, signing up or logging out:

Open-up your src/app/app.component.ts file and add this code:

/*
  file-name: app.component.ts
  *****
  The important code for logging-in, signing-up or logging-out are:
  — import 'AuthService'
  — declare variable 'email' and 'password'
  — inject service 'authService' at constructor
  — method for signup()
  — method for login()
  — method for logout()
*/

...
import { AuthService } from './service/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent {
  email: string;
  password: string;
  ...

  constructor(public authService: AuthService) {
    ...
  }


  signup() {
    this.authService.signup(this.email, this.password);
    this.email = this.password = '';
  }

  login() {
    this.authService.login(this.email, this.password);
    this.email = this.password = '';    
  }

  logout() {
    this.authService.logout();
  }
}

We inject the service (authService  at constructor) in the component’s constructor and then define local methods that call the equivalent methods on the auth service.

We inject the service (authService) with the public keyword instead of private so that we can access the service properties directly from the template too.

The template is very simple and uses the async pipe (ADD LINK TO NEW ARTICLE) on the authService’s user object to determine if a user is logged-in or not:

Open-up your src/app/app.component.html file and add this code:

<!-- 
  file-name: app.component.html
  *****
  The important code for logging-in, signing-up or logging-out, rest code you can manage yourself based on user login/logout scenerio.
  *****
  You can any time check user logging-in/out status in your template using:
  *ngIf="!(authService.user | async)"
-->

...
    <div>
        <!-- this header tag displays only when user is logged-in -->
        <h1 *ngIf="authService.user | async">
	        Welcome User: {{ (authService.user | async)?.email }}!
        </h1>

		<!-- this div displays only when user is not-logged-in -->
	    <div *ngIf="!(authService.user | async)">
            <!-- these input fields takes email and password from user -->
            <input type="text" [(ngModel)]="email" placeholder="Enter email"/>
            <input type="password" [(ngModel)]="password" placeholder="Enter password"/>

            <!-- user click this button to signup -->
            <button (click)="signup()" [disabled]="!email || !password">
            	Signup
            </button>

            <!-- user click this button to login -->
            <button (click)="login()" [disabled]="!email || !password">
            	Login
            </button>
	    </div>

        <!-- user click this button to logout -->
        <!-- this button displays only when user is logged-in -->
        <button (click)="logout()" *ngIf="authService.user | async">
        	Logout
        </button>
    </div>
...

Our input fields have two-way binding (ADD LINK TO NEW ARTICLE) to the email and password values in our component class using ngModel and the box of bananas [(ngModel)].

Done! 🤩 It’s that simple to add Firebase authentication.

See you later👋👋


Next, you may cover:

  1. How to do CRUD operations in Firebase with Firestore. (Click here👆)
  2. Deploy project to Firebase Hosting. (Click here👆)

Feel free to comment down in the comment box… If I missed anything or anything is incorrect or anything does not works for you :)
Stay connected for more articles.

GO TOP

🎉 You've successfully subscribed to Code with Chintan!
OK