How To Integrate Google Authentication In Angular 5

1
2709
Google Authentication

Angular 5 is a latest version of the angular JS framework that is developed by Google. In this article, we are going to learn how to integrate Google Authentication in Angular 5. In this article, we will use angular five as the primary database for your project. You will also learn routing for which we will use the angularfire2 component that will help us communicate with the Google firebase. We will also create a database and use the cloud Firestore in this project.

To start the project you will need a few software downloads, mainly Visual Study Code for editing the code and NodeJS. You can download both the software in the links provided below:

Visual studio code – https://code.visualstudio.com/download

Node JS – https://nodejs.org/en/

Open the command prompt as an administrator and install the Angular CLI in your system using the command below. The Angular CLI is a command line interface for angular.

Npm install -g @angular/cli

The command above will install the Angular CLI in your system and now you will need to Run the command using the code snippet below to create an Angular Project in your project folder –

“ng new angular5”

Angular CLI

Run the “code” command to open the project in visual studio code
Your should be able to see your project in visual studio code. Now go to Angular 5 project and run the following command to run the project –

“ng serve”

You will see project will run on “http://localhost:4200/

local host

Connecting to the database:

1) Go to the “https://console.firebase.google.com/” site and click on Get Started
2) Click on Add Project and create a project under the name “CMS Database”. Also select United States in the region section. Your project with the name “CMS Database” should be created.
3) Check project overview and click on “Add Firebase To Your Web App”.

Connecting to the database

The configuration section of the Firebase database should be open as shown below in the screenshot –

configuration firebase

Basically, Google does not need all the parts of this section, but just the configuration part which is this –

var config = {
    apiKey: "AIzaSyB2WLKPoC0EOpOXKQQ6oxDhLnuhuLdIH8I",
    authDomain: "cms-database-69758.firebaseapp.com",
    databaseURL: "https://cms-database-69758.firebaseio.com",
    projectId: "cms-database-69758",
    storageBucket: "cms-database-69758.appspot.com",
    messagingSenderId: "451581599848"
  };

Open your “environment.ts” file located in “C:\project\angular5\src\environments/environment.ts ” and add the code below –

// This file can be replaced during build by using the `fileReplacements` array.
// `ng build ---prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.

export const environment = {
  production: false,
firebase: {
    apiKey: "AIzaSyB2WLKPoC0EOpOXKQQ6oxDhLnuhuLdIH8I",
    authDomain: "cms-database-69758.firebaseapp.com",
    databaseURL: "https://cms-database-69758.firebaseio.com",
    projectId: "cms-database-69758",
    storageBucket: "cms-database-69758.appspot.com",
    messagingSenderId: "451581599848"
  
}
}

Now, open “environment.prod.ts” from “C:\project\angular5\src\environments” location and add this code –

import { Component } from '@angular/core';
import {environment} from './../environments/environment/environment.prod.ts';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

Install Angular fire2 with Google Authentication

Now, let’s install Angular Firebase. Check the link below to get more detailed information on Angular Fire 2.
https://github.com/angular/angularfire2

In your visual studio code, click on the View Button, you will see the integrated terminal option in the list. Open integrated terminal to execute the command below –

“npm install firebase angularfire2 –save”

Create pages.json file in your desktop and add code below

{
 "pages":{
    "angular-guide" :{
    "description": "master Angular(Angular 2+, incl. Angular 5) and build awesome, reactive web apps",
 "title" : "Angular-Guide",
 "url" : "angular2-guide"
         },
  
    "ionic3-from-scratch":{
    "description": "Create cross platform Mobile Application with Ionic 3, Angular 4, Typescript and firebase",
    "title" : "Ionic 3 From-Scratch",
 "url" : "ionic3"
         }, 
   
   "react with redux":{
    "description": "React and Redux with this tutorial as you develop apps with React Router and Webpack",
    "title" : "React with Redux",
 "url" : "react with redux"
         }, 
   "vuejs2-guide":{
    "description": "Vue JS is an awesome Javascript Framework for building fronted Application Vue Js",
    "title" : "Vue.js 2",
 "url" : "vuejs2-guide"
      } 
}
}

Now, go to the Firebase console and click on the database and select realtime database as shown below

console firebase

Click on the database, you will see your database name “CMS database” and on the right corner, you will see 3 dots that are used for importing JSON files. Click on those 3 dots and import the pages.json file from desktop.

Create new a component:

Open an integrated terminal and run the command below to install component globally

ng g component pages-list

The above command will create a new folder with the pages-list. Now,
open the “pages-list.component.ts” file and add the code below –

import { Component, OnInit } from '@angular/core';
import {AngularFireDatabase} from 'angularfire2/database';
import {Observable} from 'rxjs';

@Component({
  selector: 'pages-list',
  templateUrl: './pages-list.component.html',
  styleUrls: ['./pages-list.component.css']
})
export class PagesListComponent implements OnInit {
  pagesObservable: Observable<any[]>;

  constructor(private db: AngularFireDatabase) { }

  ngOnInit() {
    this.pagesObservable = this.getPages('/pages');

  }
  getPages(listPath): Observable<any[]> {
    return this.db.list(listPath).valueChanges();
  }
}

open “pages-list.component.html” and add code below

<ul>
  <div *ngFor="let page of pagesObservable | async">
    <h3>{{page.title}}</h3>
    <p>{{page.description}}</p>
    <div>
      <a href="{{page.url}}">Go to page</a>
    </div>
</div>
</ul>

open app.component.ts file from src folder and add code below

<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</div>
<pages-list></pages-list>

Open the “app.module.ts” file and add the code below –

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule,AngularFireDatabase} from 'angularfire2/database';


import { AppComponent } from './app.component';
import { environment } from '../environments/environment';
import { PagesListComponent } from './pages-list/pages-list.component';


@NgModule({
  declarations: [
    AppComponent,
    PagesListComponent
  ],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Open your Firebase Console and go to the database-> rules

Now, change the code to the one given below –

{
  "rules": {
    ".read": "true",
    ".write": "auth != null"
  }
}

Go to the Firebase Console and click on authentication and enable Google Authentication. Check the image below to help you further.

Firebase Console

Create A Second Component

Go to the integrated terminal and run the command below to create a component for the login-page using the code – “ng g component login-page ”

To create routing for this project, go to “C:\project\angular5\src\app” folder and create the “app-routing.module.ts” file and add the following code –

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { LoginPageComponent } from './login-page/login-page.component';
import { PagesListComponent } from './pages-list/pages-list.component';


const routes: Routes = [
    {path: '', component: PagesListComponent},
    {path: 'login', component: LoginPageComponent}    
]

@NgModule({
    imports: [
        RouterModule.forRoot(routes),
    ],
    exports: [RouterModule],
    providers: []
})
export class AppRoutingModule {}

Add the code below in the app.module.ts file. Save and close.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule,AngularFireDatabase} from 'angularfire2/database';


import { AppComponent } from './app.component';
import { environment } from '../environments/environment';
import { PagesListComponent } from './pages-list/pages-list.component';
import { LoginPageComponent } from './login-page/login-page.component';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  declarations: [
    AppComponent,
    PagesListComponent,
    LoginPageComponent
  ],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule,
    AppRoutingModule

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now, open the “pages-list.component.html” file from the page-list folder
and add the code below

<div style="text-align:center">
  <h1>
      Welcome to {{ title }}!
    </h1>
    <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
  </div>
  <ul>
    <div *ngFor="let page of pagesObservable | async">
      <h3>{{page.title}}</h3>
      <p>{{page.description}}</p>
      <div>
        <a href="{{page.url}}">Go to page</a>
      </div>
  </div>
  </ul>

Open the “app.component.html” file from the SRC folder and add code below

You are now done with this part! To check if it works, open the http://localhost:4200/loginand you will see the message login page works! as shown below

Login message

However, we still have to create a service provider, which we will do now.

To create a service provider, open an integrated terminal and run the command below to install the service providers. You will see the in-app folder and the provider folder will be created -“ng g service providers/af”

Now, inside the provider’s folder, you will see “af.service.ts” file, open this file and add the code below. Save and close.

import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable} from 'rxjs';
import * as firebase from 'firebase/app';

@Injectable()
  export class AfService {
    user: Observable<firebase.User>;
    constructor(public afAuth: AngularFireAuth)
    {
      this.user = afAuth.authState;
    }

    loginWithGoogle(){
      const provider = new firebase.auth.GoogleAuthProvider();
      this.afAuth.auth.signInWithPopup(provider);
    }

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

Open a “login-page.component.ts” file from “C:\project\angular5\src\app\login-page“location

import { Component, OnInit } from '@angular/core';
import { AfService } from '../providers/af.service';

@Component({
  selector: 'app-login-page',
  templateUrl: './login-page.component.html',
  styleUrls: ['./login-page.component.css']
})
export class LoginPageComponent implements OnInit {

  constructor(public AfService: AfService) { }

  ngOnInit() {
  }
  login(){
    this.AfService.loginWithGoogle();
  }

}

open "login-page.component.html" file from "C:\project\angular5\src\app\login-page"

<h1>Login to your account using Google</h1>
<button (click)="login()">Login</button>
<div *ngIf="AfService.user | async as user"> 

        <h3>Heelo {{user.displayName}}</h3>
    <img [src]="user.photoURL">
    <button (click)="AfService.logout() ">Logout</button>   
</div>

Open app.module.ts file from providers and add code below

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule,AngularFireDatabase} from 'angularfire2/database';


import { AppComponent } from './app.component';
import { environment } from '../environments/environment';
import { PagesListComponent } from './pages-list/pages-list.component';
import { LoginPageComponent } from './login-page/login-page.component';
import { AppRoutingModule } from './app-routing.module';
import { AfService } from './providers/af.service';
import { AngularFireAuthModule } from 'angularfire2/auth';


@NgModule({
  declarations: [
    AppComponent,
    PagesListComponent,
    LoginPageComponent
  ],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule,
    AppRoutingModule,
    AngularFireAuthModule
  ],
  providers: [AfService],
  bootstrap: [AppComponent]
})
export class AppModule { }

To check if your project is running, simply log on to your local host, in this case “http://localhost:4200/login” . Now, you can login and logout using your Google Account.

Login page

Welcome login page

1 COMMENT

  1. Thank you so much . It was Very helpful ..
    You can add one update to flush the user details completely after logged out .
    At least an option to switch other google accounts .

Leave a Reply to Anish Cancel reply

Please enter your comment!
Please enter your name here