Firebase Tutorials

How to Create Google Sign-In in Angular 13 with Firebase

In this Angular tutorial, we are going to learn how to authenticate using Firebase Google sign-in method easily. Firebase offers various social sign-in methods to make the authentication process quickly. Firebase is a robust platform which comes with a wide array of social sign-in methods.

To show you how to authenticate in an Angular app using Firebase Google sign-in method. We’ll set up an Angular 8 app from scratch and install & configure Firebase NPM module in it. Implementing Google sign-in is very simple and straightforward with Firebase, and the same way you can authenticate using other social sign-in providers, but you must have an API key to make the authentication work in your app. If you understand the working process of one social sign-in provider, then you can quickly implement other providers as well.

Firebase Sign-in Providers

  • Email/Password
  • Phone
  • Google
  • Play Games
  • Game Center (Beta)
  • Facebook
  • Twitter
  • GitHub
  • Yahoo
  • Microsoft
  • Anonymous

Prerequisite

Firstly, we’ll install and configure an Angular project from scratch. I assume you’ve already installed Node.js and Angular CLI in your system. If not follow this tutorial to Install Node JS on Mac OS

I used below command to install Angular CLI:

npm install @angular/cli -g

Setup Angular Project

Enter command in terminal and hit enter to create a fresh Angular project.

ng new angular-firebase-google-signin

# ? Would you like to add Angular routing? = Yes
# ? Which stylesheet format would you like to use? = CSS

Enter into the project directory:

cd angular-firebase-google-signin

Run command to create components:

ng g component components/log-in
ng g component components/dashboard

Enable Routing

We need to activate routing to redirect a logged in user to dashboard component, add following code in app-routing.module.ts.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LogInComponent } from './components/log-in/log-in.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';

const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'login' },
  { path: 'login', component: LogInComponent },
  { path: 'dashboard', component: DashboardComponent }
];

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

export class AppRoutingModule { }

Go to app-routing.module.html add the <router-outlet> directive.

<router-outlet></router-outlet>

Configure Firebase

Now, configure Firebase in Angular project, run the below command to install Firebase package.

npm install firebase @angular/fire --save

Add Firebase credentials in environments > environment.prod.ts :

export const environment = {
  production: true,
  firebase: {
    apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    authDomain: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    databaseURL: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    projectId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    storageBucket: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    messagingSenderId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  }
};

Import Firebase services in app.module.ts:

/* Firebase services */
import { AngularFireModule } from "@angular/fire";
import { AngularFireAuthModule } from "@angular/fire/auth";
import { environment } from '../environments/environment';

@NgModule({
  ...
  imports: [
    AngularFireAuthModule,
    AngularFireModule.initializeApp(environment.firebaseConfig)
  ]
  ...
})

export class AppModule { }

Enable Firebase Sign-in Provider

In order to make the Google sign-in work using Firebase we need to enable the sign-in provider in our Firebase app.

Go to Authentication in the Authentication tab click on Sign-in method tab. Then click on Google option and enable the sign-in provider and enter your project support email id.

Create Angular Firebase Authentication Service

Now, here comes the main part of this tutorial. We need to create a separate auth service and a user class file. In these files we’ll write the main logic to authenticate in Angular 8 app using Firebase Google Sign-in method.

Firstly, run command to create User class:

ng g i shared/user

Add the following code in shared/user.ts:

export interface User {
    uid: string;
    email: string;
    displayName: string;
    photoURL: string;
    emailVerified: boolean;
 }

Then, run command to create separate Auth service:

ng g s shared/auth

Now, add the following code in the auth.service.ts:

import { Injectable, NgZone } from '@angular/core';
import { auth } from 'firebase/app';
import { User } from "./user";
import { Router } from "@angular/router";
import { AngularFireAuth } from "@angular/fire/auth";

@Injectable({
    providedIn: 'root'
})

export class AuthService {
    user: User;

    constructor(
        public router: Router,
        public ngZone: NgZone,
        public afAuth: AngularFireAuth,
        private angularFireAuth: AngularFireAuth
    ) {
        this.afAuth.authState.subscribe(user => {
            this.user = user;
        })
    }

    // Firebase SignInWithPopup
    OAuthProvider(provider) {
        return this.afAuth.auth.signInWithPopup(provider)
            .then((res) => {
                this.ngZone.run(() => {
                    this.router.navigate(['dashboard']);
                })
            }).catch((error) => {
                window.alert(error)
            })
    }

    // Firebase Google Sign-in
    SigninWithGoogle() {
        return this.OAuthProvider(new auth.GoogleAuthProvider())
            .then(res => {
                console.log('Successfully logged in!')
            }).catch(error => {
                console.log(error)
            });
    }

    // Firebase Logout 
    SignOut() {
        return this.afAuth.auth.signOut().then(() => {
            this.router.navigate(['login']);
        })
    }

}

Using Firebase Sign-in with Google Method

We’ve successfully placed everything at it’s place, now it’s time to authenticate with Firebase Google sign-in method.

Now, we’ll import the AuthService class in log-in.component.ts and inject it to the constructor like given below:

import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/app/shared/auth.service';

@Component({
  selector: 'app-log-in',
  templateUrl: './log-in.component.html',
  styleUrls: ['./log-in.component.css']
})

export class LogInComponent implements OnInit {

  constructor(private authService: AuthService) { }

  ngOnInit() { }

}

Then, AuthService is available to the log-in component. Use the click method to call the SigninWithGoogle() method via authService. When you’ll click on the signin with Google button a popup will appear and you can log-in to Angular app’s dashboard easily.

Add the code in log-in.component.html:

<div class="flex-container">
  <div class="row">
    <div class="login-wrapper">
      <button type="button" class="large-button" (click)="authService.SigninWithGoogle()">
        <span class="large-button__icon">
          <svg viewBox="0 0 366 372" xmlns="http://www.w3.org/2000/svg">
            <path
              d="M125.9 10.2c40.2-13.9 85.3-13.6 125.3 1.1 22.2 8.2 42.5 21 59.9 37.1-5.8 6.3-12.1 12.2-18.1 18.3l-34.2 34.2c-11.3-10.8-25.1-19-40.1-23.6-17.6-5.3-36.6-6.1-54.6-2.2-21 4.5-40.5 15.5-55.6 30.9-12.2 12.3-21.4 27.5-27 43.9-20.3-15.8-40.6-31.5-61-47.3 21.5-43 60.1-76.9 105.4-92.4z"
              id="Shape" fill="#EA4335" />
            <path
              d="M20.6 102.4c20.3 15.8 40.6 31.5 61 47.3-8 23.3-8 49.2 0 72.4-20.3 15.8-40.6 31.6-60.9 47.3C1.9 232.7-3.8 189.6 4.4 149.2c3.3-16.2 8.7-32 16.2-46.8z"
              id="Shape" fill="#FBBC05" />
            <path
              d="M361.7 151.1c5.8 32.7 4.5 66.8-4.7 98.8-8.5 29.3-24.6 56.5-47.1 77.2l-59.1-45.9c19.5-13.1 33.3-34.3 37.2-57.5H186.6c.1-24.2.1-48.4.1-72.6h175z"
              id="Shape" fill="#4285F4" />
            <path
              d="M81.4 222.2c7.8 22.9 22.8 43.2 42.6 57.1 12.4 8.7 26.6 14.9 41.4 17.9 14.6 3 29.7 2.6 44.4.1 14.6-2.6 28.7-7.9 41-16.2l59.1 45.9c-21.3 19.7-48 33.1-76.2 39.6-31.2 7.1-64.2 7.3-95.2-1-24.6-6.5-47.7-18.2-67.6-34.1-20.9-16.6-38.3-38-50.4-62 20.3-15.7 40.6-31.5 60.9-47.3z"
              fill="#34A853" /></svg>
        </span>
        <span class="large-button__text">Sign in with Google</span>
      </button>
    </div>
  </div>
</div>

Conclusion

In this Angular and Firebase tutorial, we’ve learned how to authenticate using Firebase Google Sign-in method. Please share with others if you liked this tutorial and you can find the GitHub repo link below.

GitHub Repo

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.

Recent Posts

React Redux Handle API Calls with Thunk Middleware Tutorial

In this post, we will learn how to work with HTTP requests in the Redux…

1 day ago

Node AJAX Retrieve Records from MySQL Database Tutorial

MySQL is a relational database management system based on SQL – Structured Query Language, and…

4 days ago

React Manage REST API State Globally with Context API Tutorial

React Js Handle Rest API data globally with Context and useState hook tutorial. In this…

1 week ago

How to Delete Data from MySQL Database using Node Js

Node js delete data from MySQL database tutorial; Throughout this guide, you will ascertain how…

1 week ago

Node Import CSV File Data to MySQL Database with HTML Form

In this tutorial, you will discover how to import CSV file into MySQL database using…

2 weeks ago

How to Handle Global State in React js using Context API

React Js Global state management with createContext hook example; In this tutorial, we will help…

2 weeks ago