Firebase Authentication in Angular 15 with AngularFire2

Last Updated on by in Angular
Firebase Authentication in Angular 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:

  • signInWithEmailAndPassword
  • email/password signup

Error: — No Property Access From Index Signature

To resolve error:

Property ‘xxxName’ comes from an index signature, so it must be accessed with [‘xxxName’]

This setting makes sure profound consistency between accessing a field via the “dot” (obj.key) syntax, and “indexed” (obj["key"]) and the way which the property is declared in the type.

Without this flag, TypeScript will allow you to use the dot syntax to access fields which are not defined:

Make sure to set noPropertyAccessFromIndexSignature property to false under compilerOptions in tsconfig.json file:

"compilerOptions": {
 ...
 ...
   "strict": false,
   "noPropertyAccessFromIndexSignature": false,
 ...
 ...
}

Install & Configure AngularFire2

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 beginner in Firebase then you must go through this tutorial: Set up Firebase Account | Setup AngularFire2 Library in Angular

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 @angular/fire firebase@9.16.0 --legacy-peer-deps

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 { }

Create 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.

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 Firebase authentication tutorial we are using signInWithEmailAndPassword, createUserWithEmailAndPassword and signOut methods.

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

In this final part of this Firebase authentication tutorial, we are going to consume the Angular 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.scss']
})

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 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 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.