DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Add Material-UI Table In ReactJS Application
  • Create User Registration and Login Using Web API and ReactJS
  • CRUD Operations Using ReactJS Hooks and Web API
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Trending

  • Navigating and Modernizing Legacy Codebases: A Developer's Guide to AI-Assisted Code Understanding
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • The Role of AI in Identity and Access Management for Organizations
  • What’s Got Me Interested in OpenTelemetry—And Pursuing Certification
  1. DZone
  2. Data Engineering
  3. Databases
  4. Login With Google Using ReactJS

Login With Google Using ReactJS

Learn how to integrate a Google login button to securely log into an application using ReactJS.

By 
Sanwar Ranwa user avatar
Sanwar Ranwa
DZone Core CORE ·
Feb. 26, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
48.8K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

In this article, we will learn the step-by-step process of allowing users to log into an application with Gmail using ReactJS. Login 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 to Google to give the app permission. In response, the user receives a Token key and other personal details.

Prerequisites:

  • Basic knowledge of ReactJS and Web API
  • Visual Studio and Visual Studio code
  • SQL Server Management Studio

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

You may also like: Login With Facebook and Google Using Angular 8

Create ReactJS Project

Create a ReactJS  project by using the following command:

Shell
 




x


 
1
npx create-react-app sociallogin



Open the newly-created project in Visual Studio Code and install Reactstrap and Bootstrap in this project by using the following commands respectively. Learn more about Reactstrap.

Shell
 




xxxxxxxxxx
1


 
1
npm install --save bootstrap    
2
npm install --save reactstrap react react-dom



Now, open the index.js file and add import Bootstrap.

Shell
 




xxxxxxxxxx
1


 
1
import 'bootstrap/dist/css/bootstrap.min.css';  



Now install the Axios library by using the following command. Learn more about Axios.

Shell
 




xxxxxxxxxx
1


 
1
npm install --save axios  



Now install the react-google-login React plugin using the following command:

Shell
 




xxxxxxxxxx
1


 
1
npm install react-google-login --save 



Create a Google App and select "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

Now, in Visual Studio Code, go to the src folder and create a new folder. Inside this folder add two new components: Logintbygoogle.js, and Dashboard.js.

Add Routing in ReactJS

Install react-router-dom package by using the following command:

Shell
 




xxxxxxxxxx
1


 
1
npm install react-router-dom --save



Open app.js file and imports of Router and Route (react-router-dom) and two components:

JavaScript
 




xxxxxxxxxx
1


 
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:

JavaScript
 




xxxxxxxxxx
1
25


 
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} ></Route>    
15
          <Route path='/Dashboard' component={Dashboard} ></Route>     
16
        </Switch>    
17
      </div>    
18
    </Router>    
19
    </div>  
20
   </>
21
  );
22
}
23

          
24
export default App;
25

          


Now, open the Logintbygoogle.js file and add the following code.

Java
 




xxxxxxxxxx
1
69


 
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
    // this.signup = this
14
    //   .signup
15
    //   .bind(this);
16
  }
17
  signup(res) {
18
    const googleresponse = {
19
      Name: res.profileObj.name,
20
      email: res.profileObj.email,
21
      token: res.googleId,
22
      Image: res.profileObj.imageUrl,
23
      ProviderId: 'Google'
24

          
25
    };
26

          
27
    debugger;
28
    axios.post('http://localhost:60200/Api/Login/SocialmediaData', googleresponse)
29
      .then((result) => {
30
        let responseJson = result;
31
        sessionStorage.setItem("userData", JSON.stringify(result));
32
        this.props.history.push('/Dashboard')
33
      });
34
  };
35
  render() {
36
    const responseGoogle = (response) => {
37
      console.log(response);
38
      var res = response.profileObj;
39
      console.log(res);
40
      debugger;
41
      this.signup(response);
42
    }
43
    return (
44
      <div className="App">
45
        <div className="row">
46
          <div className="col-sm-12 btn btn-info">
47
            Login With Google Using ReactJS
48
            </div>
49
        </div>
50
        <div className="row">
51
          <div style={{ 'paddingTop': "20px" }} className="col-sm-12">
52
            <div className="col-sm-4"></div>
53
            <div className="col-sm-4">
54
              <GoogleLogin
55
                clientId="788786912619-k4tb19vgofvmn97q1vsti1u8fnf8j6pa.apps.googleusercontent.com"
56
                buttonText="Login with Google"
57
                onSuccess={responseGoogle}
58
                onFailure={responseGoogle} ></GoogleLogin>
59
            </div>
60
            <div className="col-sm-4"></div>
61
          </div>
62
        </div>
63
      </div>
64
    )
65
  }
66
}
67

          
68
export default Logintbygoogle
69

          


Now, open the Dashboard.js file and add the following code.

Java
 




xxxxxxxxxx
1
37


 
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
37

          


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."

Java
 




xxxxxxxxxx
1
13


 
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

Now open Visual Studio and create a new project.

Creating new VSC project

Creating new VSC project

Change the name to LoginApplication.

LoginApplication

LoginApplication

Choose the template as Web API.

Choosing the Web API

Choosing the Web API

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

Add Data

Add Data

Click on the "ADO.NET Entity Data Model" option and click "Add."

Entity Data Model

Entity Data Model

Select EF Designer from the database and click the "Next" button .

EF Designer

EF Designer

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

Adding connection properties

Adding connection properties

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

Table checkbox

Table checkbox

Now, our data model is successfully created. 

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

Userdetails Class

Java
 




xxxxxxxxxx
1


 
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

Java
 




xxxxxxxxxx
1


 
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 "Login controller" and add the following namespace.

Java
 




xxxxxxxxxx
1


 
1
using LoginWithSocialMedio.Models; 



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

Java
 




xxxxxxxxxx
1
42


 
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.

Java
 




xxxxxxxxxx
1


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



Now to go Visual Studio code and run the project.
Running the project

Running the project

Click on "Login with Google" button

Login with Google

Login with Google

Enter e-mail and password.  

Email and password

Email and password

Now if the login is successful, then it redirects to the dashboard page.

Dashboard page

Dashboard page

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

Further Reading

Getting Started With Google Sign-In and Spring Boot.

How to Learn React.js, Part 1: The React Road Map for Modern Web Developer.

Google (verb) Web API Database Visual Studio Code Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Add Material-UI Table In ReactJS Application
  • Create User Registration and Login Using Web API and ReactJS
  • CRUD Operations Using ReactJS Hooks and Web API
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!