Click here to Skip to main content
14,365,750 members

Login With Facebook and Google Using Angular 8

Rate this:
5.00 (5 votes)
Please Sign up or sign in to vote.
5.00 (5 votes)
8 Nov 2019CPOL
How to login with Facebook and Google using Angular 8

Introduction

In this article, we will learn the step-by-step process of allowing users to log in to an application with Facebook and Gmail using Angular 8. Login with Facebook and Google makes it safe and easy for users to use applications. When a user clicks on the Login button with Facebook or Gmail, the user is navigated to Facebook or Google to give the app permission. In response, the user receives a Token key and other personal details. We will use the angular6-social-login Angular library in the demo.

Prerequisites

Topics Covered in this Article

  • Create an Angular 8 Project
  • Create a Google App and Get client Id
  • Create a Facebook App and Get App Id
  • Create a database and table
  • Create a Web API Project
  • Install Bootstrap and Add Routing

Create an Angular 8 project by using the following command:

ng new socaillogindemo

Open the newly created project in Visual Studio code and install Bootstrap in this project by using the following command:

npm install bootstrap --save

Install SocialLoginModule

Now, install angular6-social-login package by using the following command:

npm install angular-6-social-login

Create a Google App and Get client Id. The first thing we need is to create a Google Project to get user credentials. Go to the Google API Console and click on Credentials. Click on Create Credentials and choose OAuth client ID.

Google API Console Credentials

Google API Console Credentials

Select web application, enter your project URL, and click on the Create button.

Creating OAuth client ID

Creating OAuth client ID

It will create a client ID and secret key.

OAuth Client

OAuth Client

Create a Facebook App and Get App Id

Go to Facebook's developer page and create a new application.

Creating new app ID

Creating a new app ID

Click on Create App ID.

Adding a product to application

Adding a product to application

Click on the setup button for Facebook Login.

Quickstart to add login

Quickstart to add login

Click on Web.

Adding site URL

Adding site URL

Enter your application's URL and click on save. Now, go to Settings.

Opening application settings

Opening application settings

Now, open the project in Visual Studio code and create two components. To create the components, open terminal and use the following commands:

ng g c Login --spec=false 
ng g c Dashboard --spec=false

Create a class named "socialusers" and add the following properties in the class:

export class Socialusers {  
    provider: string;  
    id: string;  
    email: string;  
    name: string;  
    image: string;  
    token?: string;  
    idToken?: string;  
}

Create a service named "sociallogin" to call the Web API.

Open the social login service and import the required packages and classes. Then, add the following lines of code in sociallogin.service.ts file.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class SocialloginService {
url;
  constructor(private http: HttpClient) { }
  Savesresponse(responce)
  {
    this.url =  'http://localhost:64726/Api/Login/Savesresponse';
    return this.http.post(this.url,responce);
  }
}

Project Structure

Let's check the project structure of the Angular application.

Angular application structure

Angular application structure

Now, open app.module.ts and import Social Login Module, Google and Facebook Login Providers, and AuthService. In this file, add the Facebook and Google client id that we generate when creating a Facebook and Google app. Then, add the following code to the file:

import { BrowserModule } from '@angular/platform-browser';  
import { HttpClientModule } from '@angular/common/http';  
import { NgModule } from '@angular/core';  
import { AppComponent } from './app.component';  
import { GoogleLoginProvider, FacebookLoginProvider, AuthService } 
         from 'angular-6-social-login';  
import { SocialLoginModule, AuthServiceConfig } from 'angular-6-social-login';  
import { LoginComponent } from './login/login.component';  
import { DashboardComponent } from './dashboard/dashboard.component';  
import { AppRoutingModule } from '../app/app-routing.module';  
export function socialConfigs() {  
  const config = new AuthServiceConfig(  
    [  
      {  
        id: FacebookLoginProvider.PROVIDER_ID,  
        provider: new FacebookLoginProvider('app -id')  
      },  
      {  
        id: GoogleLoginProvider.PROVIDER_ID,  
        provider: new GoogleLoginProvider('app-id')  
      }  
    ]  
  );  
  return config;  
}  
@NgModule({  
  declarations: [  
    AppComponent,  
    LoginComponent,  
    DashboardComponent  
  ],  
  imports: [  
    BrowserModule,  
    HttpClientModule,  
    AppRoutingModule  
  ],  
  providers: [  
    AuthService,  
    {  
      provide: AuthServiceConfig,  
      useFactory: socialConfigs  
    }  
  ],  
  bootstrap: [AppComponent]  
})  
export class AppModule { }

Open login.component.ts file and add the following code:

import { Component, OnInit } from '@angular/core';  
import { GoogleLoginProvider, FacebookLoginProvider, AuthService } 
         from 'angular-6-social-login';  
import { SocialLoginModule, AuthServiceConfig } from 'angular-6-social-login';  
import { Socialusers } from '../Models/socialusers'  
import { SocialloginService } from '../Service/sociallogin.service';  
import { Router, ActivatedRoute, Params } from '@angular/router';  
@Component({  
  selector: 'app-login',  
  templateUrl: './login.component.html',  
  styleUrls: ['./login.component.css']  
})  
export class LoginComponent implements OnInit {  
  response;  
    socialusers=new Socialusers();  
  constructor(  
    public OAuth: AuthService,  
    private SocialloginService: SocialloginService,  
    private router: Router  
  ) { }  
  ngOnInit() {  
  }  
  public socialSignIn(socialProvider: string) {  
    let socialPlatformProvider;  
    if (socialProvider === 'facebook') {  
      socialPlatformProvider = FacebookLoginProvider.PROVIDER_ID;  
    } else if (socialProvider === 'google') {  
      socialPlatformProvider = GoogleLoginProvider.PROVIDER_ID;  
    }  
    this.OAuth.signIn(socialPlatformProvider).then(socialusers => {  
      console.log(socialProvider, socialusers);  
      console.log(socialusers);  
      this.Savesresponse(socialusers);  
    });  
  }  
  Savesresponse(socialusers: Socialusers) {  
    this.SocialloginService.Savesresponse(socialusers).subscribe((res: any) => {  
      debugger;  
      console.log(res);  
      this.socialusers=res;  
      this.response = res.userDetail;  
      localStorage.setItem('socialusers', JSON.stringify( this.socialusers));  
      console.log(localStorage.setItem('socialusers', JSON.stringify(this.socialusers)));  
      this.router.navigate([`/Dashboard`]);  
    })  
  }  
}

Open login.component.html file and add the following lines:

<div class="container" style="padding-top:60px;">  
    <div class="row">  
        <div class="col-md-6 mx-auto">  
            <div class="card-group">  
                <div class="card p-4">  
                    <div class="card-body">  
                        <form name="form">  
                            <!-- <button class="btn btn-primary" 
                            style="text-align:center">Login</button>   -->  
                            <button type="submit" class="btn btn-block btn-success">
                             Login</button>  
                            <div style="padding-top: 20px;" class="input-group mb-3">  
                                <div class="input-group-prepend">  
                                    <span class="input-group-text">
                                    <i class="icon-user"></i></span>  
                                </div>  
                                <input type="text" name="UserName" 

                                 class="form-control sty1" placeholder="Email"  

                                    required>  
                            </div>  
                            <div class="input-group mb-4">  
                                <div class="input-group-prepend">  
                                    <span class="input-group-text">
                                    <i class="icon-lock"></i></span>  
                                </div>  
                                <input type="password" name="Passward" 

                                 class="form-control" placeholder="Password">  
                            </div>  
                            <div>  
                                <p style="color:#E92626;font-size:20px;
                                 font-weight:normal" Class="success" align="left">  
                                    {{errorMessage}}  
                                </p>  
                            </div>  
                            <div class="row">  
                                <div class="col-6">  
                                    <button type="submit" class="btn btn-primary px-4">
                                     Login</button>  
                                </div>  
                                <div class="col-6 text-right">  
                                    <button type="button" class="btn btn-link px-0">
                                     Forgot password?</button>  
                                </div>  
                            </div>  
                        </form>  
                            <hr style="border-top: 1px solid #eee;">  
                            <div class="row">  
                                <div class="col-6">  
                                    <button (click)="socialSignIn('facebook')" 

                                     class="loginBtn loginBtn--facebook">  
                                        Login with Facebook  
                                    </button>  
 
                                </div>  
                                <div class="col-6 text-right">  
                                    <button (click)="socialSignIn('google')" 

                                     class="loginBtn loginBtn--google">  
                                        Login with Google  
                                    </button>  
                                </div>  
                            </div>  
                    </div>  
                </div>  
            </div>  
        </div>  
    </div>  
</div>

Open dashboard.component.ts file and add the following lines:

import { Component, OnInit } from '@angular/core';  
import { SocialLoginModule, AuthServiceConfig, AuthService } from 'angular-6-social-login';  
import { Socialusers } from '../Models/socialusers'  
import { SocialloginService } from '../Service/sociallogin.service';  
import { Router } from '@angular/router';  
@Component({  
  selector: 'app-dashboard',  
  templateUrl: './dashboard.component.html',  
  styleUrls: ['./dashboard.component.css']  
})  
export class DashboardComponent implements OnInit {  
  socialusers = new Socialusers();  
  constructor(public OAuth: AuthService,    private router: Router) { }  
  ngOnInit() {  
    this.socialusers = JSON.parse(localStorage.getItem('socialusers'));  
    console.log(this.socialusers.image);  
  }  
  logout() {  
   alert(1);  
    this.OAuth.signOut().then(data => {  
      debugger;  
      this.router.navigate([`/Login`]);  
    });  
  }  
}

Open dashboard.component.html file and add the following lines:

<nav style="background-color: #1e7e34 !important" 

 class="navbar navbar-expand-lg navbar-light bg-light">  
    <div class="collapse navbar-collapse" id="navbarSupportedContent">  
      <ul class="navbar-nav mr-auto">  
        <li class="nav-item active">  
          <a class="nav-link" href="#">Home <span class="sr-only"></span></a>  
        </li>  
        <li class="nav-item">  
          <a class="nav-link" href="#">About</a>  
        </li>  
      </ul>  
      <form class="form-inline my-2 my-lg-0">  
          <a class="nav-link">{{this.socialusers.name}} <span class="sr-only"></span></a>  
        <button (click)="logout()" class="btn btn-outline-success my-2 my-sm-0" >
         Logout</button>  
      </form>  
    </div>  
  </nav>

Open app-routing.module.ts file and add the following code to create routing:

import { NgModule } from '@angular/core';    
import { Routes, RouterModule } from '@angular/router';    
import { DashboardComponent } from './dashboard/dashboard.component';    
import { LoginComponent } from './login/login.component';    
export const routes: Routes = [    
  {    
    path: '',    
    redirectTo: 'login',    
    pathMatch: 'full',    
  },    
  {    
    path: 'login',    
    component: LoginComponent,    
    data: {    
      title: 'Login Page'    
    }    
  },    
  {    
    path: 'Dashboard',    
    component: DashboardComponent,    
    data: {    
      title: 'Dashboard Page'    
    }    
  },       
];    
@NgModule({    
  imports: [RouterModule.forRoot(routes)],    
  exports: [RouterModule]    
})    
export class AppRoutingModule { }

Create a Web API Project

Open Visual Studio and create a new project.

Creating a new project in VS Code

Creating a new project in VS Code

Change the name as SocialmediaLogin and Click OK > Select Web API as its template.

Selecting Web API

Selecting Web API

Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.

Adding a new item

Adding a new item

Click on the "ADO.NET Entity Data Model" option and click "Add." Select "EF designer" from the database, and click the "Next" button.

Choose model contents

Choosing model contents

Add the connection properties and select database name on the next page and click OK.

Connection properties

Connection properties

Check the Table checkbox. The internal options will be selected by default. Now, click the "Finish" button.

Choosing database objects and settings

Choosing database objects and settings

Now, our data model has been successfully created.

Next, right-click on the model folder and add two classes — Users and Response. Now, paste the following code in these classes.

Response Class

public class Response
    {
        public string Status { set; get; }
        public string Message { set; get; }
    }

Users Class

    public class Users
    {
        public string name { get; set; }
        public string email { get; set; }
        public string provider { get; set; }
        public string provideid { get; set; }
        public string image { get; set; }
        public string token { get; set; }
        public string idToken { get; set; } 
    }
}

Right-click on the Controllers folder and add a new controller. Name it as "Login controller" and add the following namespace.

using LoginApplication.Models;

Create a method in this controller to save data. Add the following code in this controller.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using SocailMediaLogin.Models;
namespace SocailMediaLogin.Controllers
{
    public class LoginController : ApiController
    {
        [Route("Api/Login/Savesresponse")]
        [HttpPost]
        public object Savesresponse(Users user)
        {
            try
            {
                SocialLoginEntities DB = new SocialLoginEntities();
                Socaillogin Social= new Socaillogin();
                if (Social.TId == 0)
                {
                    Social.name = user.name;
                    Social.email = user.email;
                    Social.provideid = user.provideid;
                    Social.provider = user.provider;
                    Social.image = user.image;
                    Social.token = user.token;
                    Social.idToken = user.idToken;
                    var a=  DB.Socaillogins.Add(Social);
                    DB.SaveChanges();
                    return a;
                }
            }
            catch (Exception)
            {
                throw;
            }
            return new Response
            { Status = "Error", Message = "Invalid Data." };
        }
    }
}

Now, let's enable Cors. Go to Tools, open NuGet Package Manager, search for Cors, and install the Microsoft.Asp.Net.WebApi.Cors package. Open Webapiconfig.cs, and add the following lines:

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

Now, go to Visual Studio code and run the project and check the result:

Original sign in page

Original sign-in page

Click on Login with the Google button.

Signing in with Google

Signing in with Google

It will redirect to the Google account. Then, click on the mail id.

Signing in with Google

Signing in with Google

Enter the password and click on Next. It will redirect to the dashboard page.

Check the data in the database table to make sure that users' details are saved in the table.

In the same way, we can log in with Facebook, by clicking on the Login with Facebook button.

Summary

In this article, we discussed the process of logging in with Facebook and Google in an application using Angular 8 and Web API.

History

  • 8th November, 2019: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sanwar ranwa
Software Developer
India India
I am full stack dot net Developer. I hold Bachelor degree in Information Tech. My main skills are C#, ASP.Net MVP ,Angular and ReactJS


Comments and Discussions

 
QuestionHay Pin
thietbivietavn8-Nov-19 16:18
professionalthietbivietavn8-Nov-19 16:18 
Thanks YOu

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Article
Posted 8 Nov 2019

Tagged as

Stats

2.4K views
8 bookmarked