Login With Facebook And Google Using Angular 8

In this article, you will learn about Login with Facebook and Google using Angular 8.

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. Logging in 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
  • Basic knowledge of Angular and Web API
  • Visual Studio
  • Visual Studio Code
  • SQL Server Management Studio
This article covers the following,
  • Create 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 Angular 8 Project

 
Create an Angular 8 project by using the following command.
  1. ng new socaillogindemo  
Open the newly created project in visual studio code and install bootstrap in this project by using the following command
  1. npm install bootstrap --save  
Install SocialLoginModule
 
Now install angular6-social-login package by using following command
  1. npm install angular6-social-login  

Create a Google App and Get client Id

 
The first thing we need to create Google Project, is to get Credentials.
 
 
Login With Facebook And Google Using Angular 8
 
Click on create Credentials and Choose OAuth client ID.
 
Login With Facebook And Google Using Angular 8
 
Select web application and enter your project url and click on Create button,
 
Login With Facebook And Google Using Angular 8
 
It will create client ID and secret key. 
 
Login With Facebook And Google Using Angular 8
 

Create a Facebook App and Get App Id

 
Go to Facebook developer page and create a new App,
 
Login With Facebook And Google Using Angular 8
 
Click on create App ID
 
Login With Facebook And Google Using Angular 8
 
Click on create App ID
 
Login With Facebook And Google Using Angular 8
 
Click on Web
 
Login With Facebook And Google Using Angular 8
 
Enter Site url and click on save, now go to setting
 
Login With Facebook And Google Using Angular 8
 
Now open the project in visual studio code and create two components. To create the components, open terminal and use the following commands.
  1. ng g c Login --spec=false  
  2. ng g c Dashborad--spec=false  

Login component

 
Dashboard component
 
Create a class named "socialusers" and add Add following properties in the class.
  1. export class Socialusers {    
  2.     provider: string;    
  3.     id: string;    
  4.     email: string;    
  5.     name: string;    
  6.     image: string;    
  7.     token?: string;    
  8.     idToken?: string;    
  9. }     
Create a service named "sociallogin" to call the Web API.
 
Open the sociallogin service and import required packages and classes. Add the following lines of code in the sociallogin.service.ts file.
  1. import { Injectable } from '@angular/core';    
  2. import { HttpClient } from '@angular/common/http';    
  3. @Injectable({    
  4.   providedIn: 'root'    
  5. })    
  6. export class SocialloginService {    
  7. url;    
  8.   constructor(private http: HttpClient) { }    
  9.     
  10.   Savesresponse(responce)    
  11.   {    
  12.     this.url =  'http://localhost:64726/Api/Login/Savesresponse';    
  13.     return this.http.post(this.url,responce);    
  14.   }    
  15. }    

Project Structure

 
Let's check the project structure of the angular application.
 
Login With Facebook And Google Using Angular 8
 
Now open app.module.ts and import Social Login Module and Google and Facebook Login Providers and AuthService. In this file, we add the Facebook and Google client id that we generated when creating the  Facebook and Google app. Add the following code in this file.
  1. import { BrowserModule } from '@angular/platform-browser';    
  2. import { HttpClientModule } from '@angular/common/http';    
  3. import { NgModule } from '@angular/core';    
  4. import { AppComponent } from './app.component';    
  5. import { GoogleLoginProvider, FacebookLoginProvider, AuthService } from 'angular-6-social-login';    
  6. import { SocialLoginModule, AuthServiceConfig } from 'angular-6-social-login';    
  7. import { LoginComponent } from './login/login.component';    
  8. import { DashboardComponent } from './dashboard/dashboard.component';    
  9. import { AppRoutingModule } from '../app/app-routing.module';    
  10. export function socialConfigs() {    
  11.   const config = new AuthServiceConfig(    
  12.     [    
  13.       {    
  14.         id: FacebookLoginProvider.PROVIDER_ID,    
  15.         provider: new FacebookLoginProvider('app -id')    
  16.       },    
  17.       {    
  18.         id: GoogleLoginProvider.PROVIDER_ID,    
  19.         provider: new GoogleLoginProvider('app-id')    
  20.       }    
  21.     ]    
  22.   );    
  23.   return config;    
  24. }    
  25. @NgModule({    
  26.   declarations: [    
  27.     AppComponent,    
  28.     LoginComponent,    
  29.     DashboardComponent    
  30.   ],    
  31.   imports: [    
  32.     BrowserModule,    
  33.     HttpClientModule,    
  34.     AppRoutingModule    
  35.   ],    
  36.   providers: [    
  37.     AuthService,    
  38.     {    
  39.       provide: AuthServiceConfig,    
  40.       useFactory: socialConfigs    
  41.     }    
  42.   ],    
  43.   bootstrap: [AppComponent]    
  44. })    
  45. export class AppModule { }    
Open login.component.ts file and add the following code
  1. import { Component, OnInit } from '@angular/core';    
  2. import { GoogleLoginProvider, FacebookLoginProvider, AuthService } from 'angular-6-social-login';    
  3. import { SocialLoginModule, AuthServiceConfig } from 'angular-6-social-login';    
  4. import { Socialusers } from '../Models/socialusers'    
  5. import { SocialloginService } from '../Service/sociallogin.service';    
  6. import { Router, ActivatedRoute, Params } from '@angular/router';    
  7. @Component({    
  8.   selector: 'app-login',    
  9.   templateUrl: './login.component.html',    
  10.   styleUrls: ['./login.component.css']    
  11. })    
  12. export class LoginComponent implements OnInit {    
  13.   response;    
  14.     socialusers=new Socialusers();    
  15.   constructor(    
  16.     public OAuth: AuthService,    
  17.     private SocialloginService: SocialloginService,    
  18.     private router: Router    
  19.   ) { }    
  20.     
  21.   ngOnInit() {    
  22.   }    
  23.   public socialSignIn(socialProvider: string) {    
  24.     let socialPlatformProvider;    
  25.     if (socialProvider === 'facebook') {    
  26.       socialPlatformProvider = FacebookLoginProvider.PROVIDER_ID;    
  27.     } else if (socialProvider === 'google') {    
  28.       socialPlatformProvider = GoogleLoginProvider.PROVIDER_ID;    
  29.     }    
  30.     
  31.     this.OAuth.signIn(socialPlatformProvider).then(socialusers => {    
  32.       console.log(socialProvider, socialusers);    
  33.       console.log(socialusers);    
  34.       this.Savesresponse(socialusers);    
  35.     
  36.     });    
  37.   }    
  38.   Savesresponse(socialusers: Socialusers) {    
  39.     
  40.     this.SocialloginService.Savesresponse(socialusers).subscribe((res: any) => {    
  41.       debugger;    
  42.       console.log(res);    
  43.       this.socialusers=res;    
  44.       this.response = res.userDetail;    
  45.       localStorage.setItem('socialusers', JSON.stringify( this.socialusers));    
  46.       console.log(localStorage.setItem('socialusers', JSON.stringify(this.socialusers)));    
  47.       this.router.navigate([`/Dashboard`]);    
  48.     })    
  49.   }    
  50. }    
Open login.component.html file and add the following lines
  1. <div class="container" style="padding-top:60px;">    
  2.     <div class="row">    
  3.         <div class="col-md-6 mx-auto">    
  4.             <div class="card-group">    
  5.                 <div class="card p-4">    
  6.                     <div class="card-body">    
  7.                         <form name="form">    
  8.                             <!-- <button class="btn btn-primary" style="text-align:center">Login</button>   -->    
  9.                             <button type="submit" class="btn btn-block btn-success">Login</button>    
  10.                             <div style="padding-top: 20px;" class="input-group mb-3">    
  11.                                 <div class="input-group-prepend">    
  12.                                     <span class="input-group-text"><i class="icon-user"></i></span>    
  13.                                 </div>    
  14.                                 <input type="text" name="UserName" class="form-control sty1" placeholder="Email"    
  15.                                     required>    
  16.                             </div>    
  17.                             <div class="input-group mb-4">    
  18.                                 <div class="input-group-prepend">    
  19.                                     <span class="input-group-text"><i class="icon-lock"></i></span>    
  20.                                 </div>    
  21.                                 <input type="password" name="Passward" class="form-control" placeholder="Password">    
  22.                             </div>    
  23.                             <div>    
  24.                                 <p style="color:#E92626;font-size:20px;font-weight:normal" Class="success" align="left">    
  25.                                     {{errorMessage}}    
  26.                                 </p>    
  27.                             </div>    
  28.                             <div class="row">    
  29.                                 <div class="col-6">    
  30.                                     <button type="submit" class="btn btn-primary px-4">Login</button>    
  31.                                 </div>    
  32.                                 <div class="col-6 text-right">    
  33.                                     <button type="button" class="btn btn-link px-0">Forgot password?</button>    
  34.                                 </div>    
  35.                             </div>    
  36.                         </form>    
  37.                             <hr style="border-top: 1px solid #eee;">    
  38.                             <div class="row">    
  39.                                 <div class="col-6">    
  40.                                     <button (click)="socialSignIn('facebook')" class="loginBtn loginBtn--facebook">    
  41.                                         Login with Facebook    
  42.                                     </button>    
  43.                                        
  44.                                 </div>    
  45.                                 <div class="col-6 text-right">    
  46.                                     <button (click)="socialSignIn('google')" class="loginBtn loginBtn--google">    
  47.                                         Login with Google    
  48.                                     </button>    
  49.                                 </div>    
  50.                             </div>    
  51.                     </div>    
  52.                 </div>    
  53.             </div>    
  54.         </div>    
  55.     </div>    
  56. </div>    
Open dashboard.component.ts file and add the following lines
  1. import { Component, OnInit } from '@angular/core';    
  2. import { SocialLoginModule, AuthServiceConfig, AuthService } from 'angular-6-social-login';    
  3. import { Socialusers } from '../Models/socialusers'    
  4. import { SocialloginService } from '../Service/sociallogin.service';    
  5. import { Router } from '@angular/router';    
  6. @Component({    
  7.   selector: 'app-dashboard',    
  8.   templateUrl: './dashboard.component.html',    
  9.   styleUrls: ['./dashboard.component.css']    
  10. })    
  11. export class DashboardComponent implements OnInit {    
  12.   socialusers = new Socialusers();    
  13.   constructor(public OAuth: AuthService,    private router: Router) { }    
  14.     
  15.   ngOnInit() {    
  16.     this.socialusers = JSON.parse(localStorage.getItem('socialusers'));    
  17.   }    
  18.   logout() {    
  19.     this.OAuth.signOut().then(data => {    
  20.       debugger;    
  21.       this.router.navigate([`/Login`]);    
  22.     });    
  23.   }    
  24.     
  25. }    
Open dashboard.component.html file and add the following lines
  1. <nav style="background-color: #1e7e34 !important" class="navbar navbar-expand-lg navbar-light bg-light">    
  2.     <div class="collapse navbar-collapse" id="navbarSupportedContent">    
  3.       <ul class="navbar-nav mr-auto">    
  4.         <li class="nav-item active">    
  5.           <a class="nav-link" href="#">Home <span class="sr-only"></span></a>    
  6.         </li>    
  7.         <li class="nav-item">    
  8.           <a class="nav-link" href="#">About</a>    
  9.         </li>    
  10.       </ul>    
  11.       <form class="form-inline my-2 my-lg-0">    
  12.           <a class="nav-link">{{this.socialusers.name}} <span class="sr-only"></span></a>    
  13.         <button (click)="logout()" class="btn btn-outline-success my-2 my-sm-0" >Logout</button>    
  14.       </form>    
  15.     </div>    
  16.   </nav>    

Create a Web API Project

 
Open Visual Studio and create a new project.
 
Login With Facebook And Google Using Angular 8
 
Change the name as SocialmediaLogin and Click ok > Select Web API as its template.
 
Login With Facebook And Google Using Angular 8
 
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
Login With Facebook And Google Using Angular 8
 
Click on the "ADO.NET Entity Data Model" option and click "Add." Select "EF designer" from the database, and click the "Next" button.
 
Login With Facebook And Google Using Angular 8
 
Add the connection properties and select database name on the next page and click OK.
 
Login With Facebook And Google Using Angular 8
 
Check the table checkbox. The internal options will be selected by default. Now, click the "Finish" button. 
 
Login With Facebook And Google Using Angular 8
 
Now, our data model is successfully created.
 
Now, Right-click on model folder and add two classes -Users and Response. Now, paste the following code in these classes.
 
Users Class
  1. public class Users    
  2.    {    
  3.        public string name { get; set; }    
  4.        public string email { get; set; }    
  5.        public string provider { get; set; }    
  6.        public string provideid { get; set; }    
  7.        public string image { get; set; }    
  8.        public string token { get; set; }    
  9.        public string idToken { get; set; }     
  10.    }   
Response Class
  1. public class Response    
  2.    {    
  3.        public string Status { set; get; }    
  4.        public string Message { set; get; }    
  5.    }    
Right-click on the Controllers folder and add a new controller. Name it as "Login controller" and add the following namespace.
  1. using SocailMediaLogin.Models;    
Create a method in this controller to save data. Add the following code in this controller.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Net;    
  5. using System.Net.Http;    
  6. using System.Web.Http;    
  7. using SocailMediaLogin.Models;    
  8. namespace SocailMediaLogin.Controllers    
  9. {    
  10.     public class LoginController : ApiController    
  11.     {    
  12.         [Route("Api/Login/Savesresponse")]    
  13.         [HttpPost]    
  14.         public object Savesresponse(Users user)    
  15.         {    
  16.             try    
  17.             {    
  18.                 SocialLoginEntities DB = new SocialLoginEntities();    
  19.                 Socaillogin Social= new Socaillogin();    
  20.                 if (Social.TId == 0)    
  21.                 {    
  22.                     Social.name = user.name;    
  23.                     Social.email = user.email;    
  24.                     Social.provideid = user.provideid;    
  25.                     Social.provider = user.provider;    
  26.                     Social.image = user.image;    
  27.                     Social.token = user.token;    
  28.                     Social.idToken = user.idToken;    
  29.                     var a=  DB.Socaillogins.Add(Social);    
  30.                     DB.SaveChanges();    
  31.                     return a;    
  32.                 }    
  33.             }    
  34.             catch (Exception)    
  35.             {    
  36.     
  37.                 throw;    
  38.             }    
  39.             return new Response    
  40.             { Status = "Error", Message = "Invalid Data." };    
  41.         }    
  42.     }    
  43. }    
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.
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");  
  2. config.EnableCors(cors);  
Now to go Visual Studio code and run the project
 Login With Facebook And Google Using Angular 8
Click on Login with Google button
 
Login With Facebook And Google Using Angular 8
 
Click on the mail id,
 
Login With Facebook And Google Using Angular 8
 
Enter the password and click next button,
 
Login With Facebook And Google Using Angular 8
 
In the same way, click on Login with facebook button and check.
 

Summary

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