Login With Gmail Using ReactJS

Introduction

 
In this article, we will learn the step-by-step process of allowing users to log in to an application with Gmail using ReactJS. Logging in with Gmail makes it safe and easy for users to use applications. When a user clicks on the Login with Gmail button, the user is navigated Google to give the app permission. In response, the user receives a token key and other personal details.
 

Prerequisites

Topics Covered in this Article
  • Create a ReactJS Project
  • Install react-google-login React plugin
  • Install Axios and Bootstrap
  • Add React Router
  • Install Bootstrap and React strap
  • Create a Google App and get client Id
  • Create a database and table
  • Create a Web API Project
Create a ReactJS project by using the following command:
  1. npx create-react-app sociallogin     
Open the newly-created project in Visual Studio code and install react-google-login React plugin using the following command
  1. npm install react-google-login --save   
Now install Bootstrap in this project by using the following command.
  1. npm install --save bootstrap         
Now, open the index.js file and add import Bootstrap.
  1. import 'bootstrap/dist/css/bootstrap.min.css';     
Now install the Axios library by using the following command. Learn more about Axios
  1. npm install --save axios        
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.
 
 
Select web application, enter your project URL and click on the Create button.
 
 
Creating OAuth client ID
 
It will create a client ID and secret key.
 
 
Now, in Visual Studio code, go to src folder and create a new folder and inside this folder add 2 new components
1.Logintbygoogle.js
2. Dashboard.js
 

Add Routing in ReactJS

 
Install react-router-dom package by using the following command
  1. npm install react-router-dom --save  
Open app.js file and imports of Router and Route (react-router-dom) and 2 components.
  1. import Logintbygoogle from './Logintbygoogle'    
  2. import Dashboard from "./Dashboard";    
  3. import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';     
Add the following code in app.js file:
  1. import React from 'react';    
  2. import logo from './logo.svg';    
  3. import './App.css';    
  4. import Logintbygoogle from './Logintbygoogle'    
  5. import Dashboard from "./Dashboard";    
  6. import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';     
  7. function App() {    
  8.   return (    
  9.     <>    
  10.    <div className="App">      
  11.      <Router>        
  12.       <div className="container">       
  13.         <Switch>        
  14.           <Route exact path='/' component={Logintbygoogle} />        
  15.           <Route path='/Dashboard' component={Dashboard} />         
  16.         </Switch>        
  17.       </div>        
  18.     </Router>        
  19.     </div>      
  20.    </>    
  21.   );    
  22. }    
  23.     
  24. export default App;   
Now, open the Logintbygoogle.js file and add the following code.
  1. import React, { Component } from 'react'    
  2. import FacebookLogin from 'react-facebook-login';    
  3. import GoogleLogin from 'react-google-login';    
  4. import { Redirect } from 'react-router-dom';    
  5. import axios from 'axios'    
  6.     
  7. export class Logintbygoogle extends Component {    
  8.   constructor(props) {    
  9.     super(props);    
  10.     this.state = {    
  11.     
  12.     };    
  13.   }    
  14.   signup(res) {    
  15.     const googleresponse = {    
  16.       Name: res.profileObj.name,    
  17.       email: res.profileObj.email,    
  18.       token: res.googleId,    
  19.       Image: res.profileObj.imageUrl,    
  20.       ProviderId: 'Google'    
  21.     
  22.     };    
  23.     
  24.     debugger;    
  25.     axios.post('http://localhost:60200/Api/Login/SocialmediaData', googleresponse)    
  26.       .then((result) => {    
  27.         let responseJson = result;    
  28.         console.log(result.data.name);    
  29.         alert("data");    
  30.         sessionStorage.setItem("userData", JSON.stringify(result));    
  31.         this.props.history.push('/Dashboard')    
  32.       });    
  33.   };    
  34.   render() {    
  35.     const responseGoogle = (response) => {    
  36.       console.log(response);    
  37.       var res = response.profileObj;    
  38.       console.log(res);    
  39.       debugger;    
  40.       this.signup(response);    
  41.     }    
  42.     return (    
  43.       <div className="App">    
  44.         <div className="row">    
  45.           <div className="col-sm-12 btn btn-info">    
  46.             Login With Google Using ReactJS    
  47.             </div>    
  48.         </div>    
  49.         <div className="row">    
  50.           <div style={{ 'paddingTop'"20px" }} className="col-sm-12">    
  51.             <div className="col-sm-4"></div>    
  52.             <div className="col-sm-4">    
  53.               <GoogleLogin    
  54.                 clientId="788786912619-grj4cpmh0mcd35r1bjji09j2qicanv0f.apps.googleusercontent.com"    
  55.                 buttonText="Login with Google"    
  56.                 onSuccess={responseGoogle}    
  57.                 onFailure={responseGoogle} />    
  58.             </div>    
  59.             <div className="col-sm-4"></div>    
  60.           </div>    
  61.         </div>    
  62.       </div>    
  63.     )    
  64.   }    
  65. }    
  66.     
  67. export default Logintbygoogle     
Now, open the Dashboard .js file and add the following code.
  1. import React, { Component } from 'react'    
  2.     
  3. export class Dashboard extends Component {    
  4.         constructor(props){    
  5.                 super(props);    
  6.                 this.state = {    
  7.                 name:'',    
  8.                 };    
  9.                }    
  10.   componentDidMount() {    
  11.         const data = JSON.parse(sessionStorage.getItem('userData'));    
  12.         let data1=data;    
  13.         console.log(data1.data.Name);    
  14.         
  15.          console.log(data1.Name);    
  16.          this.setState({name: data1.data.Name})    
  17.       }    
  18.         render() {    
  19.                 return (    
  20.                         <div className="container">       
  21.                          <div className="row">      
  22.                                   <div className="col-sm-12 btn btn-info">      
  23.                                  Welcome to Dashboard    
  24.                          </div>      
  25.                          </div>    
  26.                          <div className="row">    
  27.                          <div className="col-sm-3"> Welcome  :{this.state.name} </div>    
  28.                          <div className="col-sm-9"></div>    
  29.                          {/* <div className="col-sm-4"></div> */}    
  30.                          </div>    
  31.                         </div>    
  32.                 )    
  33.         }    
  34. }    
  35.     
  36. export default Dashboard     

Create a table in the Database

 
Open SQL Server Management Studio, create a database named "Demotest," and in this database, create a table. Give that table a name like "sociallogin".
  1. CREATE TABLE [dbo].[Socaillogin](    
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,    
  3.     [Name] [varchar](50) NULL,    
  4.     [Email] [varchar](50) NULL,    
  5.     [ProviderName] [varchar](50) NULL,    
  6.     [Image] [varchar](650) NULL,    
  7.     [Token] [nvarchar](650) NULL,    
  8.  CONSTRAINT [PK_Socaillogin] PRIMARY KEY CLUSTERED     
  9. (    
  10.     [Id] ASC    
  11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]    
  12. ) ON [PRIMARY]    
  13. GO     

Create a Web API Project

 
Open Visual Studio and create a new project.
 
 
Change the name as LoginApplication
 
 
Select Web API as its template.
 
 
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
 
Click on the "ADO.NET Entity Data Model" option and click "Add". 
 
  
Select the EF Designer from the database and click the "Next" button.
 
 
Add the connection properties and select database name on the next page and click OK.
 
 
Check the Table checkbox. The internal options will be selected by default. Now, click the "Finish" button.
 
 
Our data model is created successfully now. 
 
Now, Right-click on the model folder and add two classes -Userdetails and Response. Now, paste the following code in these classes.
 
Userdetails class
  1. public class Userdetails    
  2.     {    
  3.         public int Id { get; set; }    
  4.         public string Name { get; set; }    
  5.         public string Email { get; set; }    
  6.         public string ProviderName { get; set; }    
  7.         public string Image { get; set; }    
  8.         public string Token { get; set; }    
  9.     }    
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 LoginWithSocialMedio.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 LoginWithSocialMedio.Models;    
  8.     
  9. namespace LoginWithSocialMedio.Controllers    
  10. {    
  11.     [RoutePrefix("Api/Login")]    
  12.     public class LoginController : ApiController    
  13.     {    
  14.         [Route("SocialmediaData")]    
  15.         [HttpPost]    
  16.         public object SocialmediaData(Userdetails user)    
  17.         {    
  18.             try    
  19.             {    
  20.                 DemoTestEntities DB = new DemoTestEntities();    
  21.                 Socaillogin Social = new Socaillogin();    
  22.                 if (Social.Id == 0)    
  23.                 {    
  24.                     Social.Name = user.Name;    
  25.                     Social.Email = user.Email;    
  26.                     Social.ProviderName = user.ProviderName;    
  27.                     Social.Image = user.Image;    
  28.                     Social.Token = user.Token;    
  29.                     var res = DB.Socaillogins.Add(Social);    
  30.                     DB.SaveChanges();    
  31.                     return res;    
  32.                 }    
  33.             }    
  34.             catch (Exception)    
  35.             {    
  36.                 throw;    
  37.             }    
  38.             return new Response    
  39.             { Status = "Error", Message = "Data." };    
  40.         }    
  41.     }    
  42. }     
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
 
 
Click on 'login with google' button
 
 
Enter e-mail and password 
 
 
 
Now if login is successful then it redirects to the dashboard page
 
 

Summary

 
In this article, we discussed the process of logging in with Gmail using React and Web API.