Angular 8 Social Login with example

Today we will discuss about Angular 8 Social Login we will integrate facebook and google login. I am going to use JS SDK provided by Facebook and Google , So let’s get started with Angular 8 Social Login with example

Login with Google

Before start Google login in Angular 8. We need a Angular 8 Project. If you don’t know how to create a new angular 8 project. Follow this tutorial.

Create Client ID

Before you can integrate Google Sign-In into your website, you must create a client ID, which you need to call the sign-in API.

To create a Google API Console project and client ID, go to the APIs & Services dashboard and then follow the below video:

Add a Placeholder

We need to add a placeholder for the signin button. To add the placeholder open app.component.html file and put the below html markup

<div class="container mt-5">
  <h2>Google Login</h2>
  <div class="row mt-5">
    <div class="col-md-4 mt-2 m-auto ">
        <button class="loginBtn loginBtn--google" #loginRef>
            Login with Google
          </button>
    </div>    
  </div>
</div>

Next, Open the app.component.ts file and add the below code

@ViewChild('loginRef', {static: true }) loginElement: ElementRef;

Access <div #loginRef>: loginElement is a reference to <div #loginRef> inside app.component.html file. ViewChild directive creates a direct link between <div> element and a loginElement member variable.

Load the Google Platform Library

Add the below method in your component.ts file. I am going to add in my app.component.ts file

googleSDK() {

  window['googleSDKLoaded'] = () => {
    window['gapi'].load('auth2', () => {
      this.auth2 = window['gapi'].auth2.init({
        client_id: 'YOUR_CLIENT_ID',
        cookiepolicy: 'single_host_origin',
        scope: 'profile email'
      });
      this.prepareLoginButton();
    });
  }

  (function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "https://apis.google.com/js/platform.js?onload=googleSDKLoaded";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'google-jssdk'));

}

Here, Change the YOUR_CLIENT_ID with your client id, Which we have created at the start of this tutorial.

You may notice that We have created a googleSDKLoaded method. We have set the callback when the Google Platform Library will loaded. This method will initialize the google login

Next, Call the above method from then ngOnInit () method

ngOnInit() {
  this.googleSDK();
}

Attach Click Handler

Add the below method in your component.ts file. I am going to add in my app.component.ts file

prepareLoginButton() {

  this.auth2.attachClickHandler(this.loginElement.nativeElement, {},
    (googleUser) => {

      let profile = googleUser.getBasicProfile();
      console.log('Token || ' + googleUser.getAuthResponse().id_token);
      console.log('ID: ' + profile.getId());
      console.log('Name: ' + profile.getName());
      console.log('Image URL: ' + profile.getImageUrl());
      console.log('Email: ' + profile.getEmail());
      //YOUR CODE HERE


    }, (error) => {
      alert(JSON.stringify(error, undefined, 2));
    });

}

You might noticed that We have already call this method inside the ` googleSDKLoaded .

This method will attach the click handler. When user click on Google signin button google will open the login dialog box.

After the complete all the above steps, our component will looks like this

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

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

  auth2: any;

  @ViewChild('loginRef', {static: true }) loginElement: ElementRef;

  constructor() { }

  ngOnInit() {

    this.googleSDK();
  }

  prepareLoginButton() {

    this.auth2.attachClickHandler(this.loginElement.nativeElement, {},
      (googleUser) => {

        let profile = googleUser.getBasicProfile();
        console.log('Token || ' + googleUser.getAuthResponse().id_token);
        console.log('ID: ' + profile.getId());
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail());
        //YOUR CODE HERE


      }, (error) => {
        alert(JSON.stringify(error, undefined, 2));
      });

  }
  googleSDK() {

    window['googleSDKLoaded'] = () => {
      window['gapi'].load('auth2', () => {
        this.auth2 = window['gapi'].auth2.init({
          client_id: '188637199174-dnm6dm1r7k652d8ddqd122kgas9kho3e.apps.googleusercontent.com',
          cookiepolicy: 'single_host_origin',
          scope: 'profile email'
        });
        this.prepareLoginButton();
      });
    }

    (function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "https://apis.google.com/js/platform.js?onload=googleSDKLoaded";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'google-jssdk'));

  }

}

We have successfully integrate google login now we will integrate facebook login

Facebook Login

Facebook is most popular social website and another hand angular is also popular JS framework. So let’s get start with facebook login

To implement Facebook Login, you need a Facebook App ID, which you can create and retrieve in the App Dashboard. Facebook App Dashboard will looks like this

Next, Click on Add a New App. The next screen will looks like this

Enter display name and click on the Create App ID

After clicking on the Create App ID the facebook will redirect you to the Select a Scenario screen here choose Integrate Facebook Login option and click on Confirm button. Now you are in the App Dashboard which will looks like this

Here choose the Settings then Basic menu in the left hand side, will open the setting page. Here enter your website url in the App Domain input box then click on the Save Changes

Next, We will dive in the code. To do that we need a new component for the login, I will work on the app.component. so let’s get started

Access Facebook Graph API

We need Facebook sdk to make any interaction with facebook api. Let’s include Facebook Graph API in our project.

Open app.component.ts file and add the below method. You can put this code in your component.ts file

fbLibrary() {

    (window as any).fbAsyncInit = function() {
      window['FB'].init({
        appId      : '869805000070130',
        cookie     : true,
        xfbml      : true,
        version    : 'v3.1'
      });
      window['FB'].AppEvents.logPageView();
    };

    (function(d, s, id){
       var js, fjs = d.getElementsByTagName(s)[0];
       if (d.getElementById(id)) {return;}
       js = d.createElement(s); js.id = id;
       js.src = "https://connect.facebook.net/en_US/sdk.js";
       fjs.parentNode.insertBefore(js, fjs);
     }(document, 'script', 'facebook-jssdk'));

}

Here, change the appId property with your appId

You may noticed that we have declare the fbAsyncInit method, The facebook will called this method when the facebook sdk loaded completely. Under the fbAsyncInit method we have initialized the app

next, call the above method from the ngOnInit method

ngOnInit() {
    this.fbLibrary();
}

Create a facebook login button,

Next, We need a login button which will call facebook login method

Open app.component.html file and put the below html. You can put this html in your component.ts file

<div class="container mt-5">
  <h2>Facebook Login</h2>
  <div class="row mt-5">
    <div class="col-md-4 mt-2 m-auto ">
        <button class="loginBtn loginBtn--facebook" (click)="login()">
            Login with Facebook
          </button>
    </div>    
  </div>
</div>

Facebook Login

Next, We need to create a new method where we will call the facebook login method.

Open app.component.ts file and add the below method. You can put this code in your component.ts file

login() {

    window['FB'].login((response) => {
        console.log('login response',response);
        if (response.authResponse) {

          window['FB'].api('/me', {
            fields: 'last_name, first_name, email'
          }, (userInfo) => {

            console.log("user information");
            console.log(userInfo);
          });
          
        } else {
          console.log('User login failed');
        }
    }, {scope: 'email'});
}

By default facebook return only first_name, last_name and user_id. If you want more user information. You can use the scope parameter

Here is the list of parameter you can pass in the scope

https://developers.facebook.com/docs/facebook-login/permissions

Running application:

Run the application using ng serve --o

Preview

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *