Login With Google Using ReactJS





5.00/5 (1 vote)
Step-by-step process of logging in with Gmail using React and Web API
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
Create a ReactJS project by using the following command:
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.
npm install --save bootstrap
npm install --save reactstrap react react-dom
Now, open the index.js file and add import Bootstrap.
import 'bootstrap/dist/css/bootstrap.min.css';
Now install the Axios library by using the following command. Learn more about Axios.
npm install --save axios
Now install react-google-login React plugin using the following command:
npm install react-google-login --save
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.
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.
OAuth Client
Now, in Visual Studio code, go to src folder and create a new folder and inside this folder, add 2 new components:
- Logintbygoogle.js
- Dashboard.js
Add Routing in ReactJS
Install react-router-dom
package by using the following command:
npm install react-router-dom --save
Open app.js file and imports of Router and Route (react-router-dom) and 2 components:
import Logintbygoogle from './Logintbygoogle'
import Dashboard from "./Dashboard";
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
Add the following code in app.js file:
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Logintbygoogle from './Logintbygoogle'
import Dashboard from "./Dashboard";
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
function App() {
return (
<>
<router>
<switch> <route component="{Logintbygoogle}" exact=""
path="/"> <route component="{Dashboard}" path="/Dashboard">
); } export default App;
Now, open the Logintbygoogle.js file and add the following code:
import React, { Component } from 'react'
import FacebookLogin from 'react-facebook-login';
import GoogleLogin from 'react-google-login';
import { Redirect } from 'react-router-dom';
import axios from 'axios'
export class Logintbygoogle extends Component {
constructor(props) {
super(props);
this.state = {
};
// this.signup = this
// .signup
// .bind(this);
}
signup(res) {
const googleresponse = {
Name: res.profileObj.name,
email: res.profileObj.email,
token: res.googleId,
Image: res.profileObj.imageUrl,
ProviderId: 'Google'
};
debugger;
axios.post('http://localhost:60200/Api/Login/SocialmediaData', googleresponse)
.then((result) => {
let responseJson = result;
sessionStorage.setItem("userData", JSON.stringify(result));
this.props.history.push('/Dashboard')
});
};
render() {
const responseGoogle = (response) => {
console.log(response);
var res = response.profileObj;
console.log(res);
debugger;
this.signup(response);
}
return (
Login With Google Using ReactJS
<googlelogin buttontext="Login with Google"
clientid="788786912619-k4tb19vgofvmn97q1vsti1u8fnf8j6pa.apps.googleusercontent.com"
onfailure="{responseGoogle}" onsuccess="{responseGoogle}">
) } } export default Logintbygoogle
Now, open the Dasgboard .js file and add the following code:
import React, { Component } from 'react'
export class Dashboard extends Component {
constructor(props){
super(props);
this.state = {
name:'',
};
}
componentDidMount() {
const data = JSON.parse(sessionStorage.getItem('userData'));
let data1=data;
console.log(data1.data.Name);
console.log(data1.Name);
this.setState({name: data1.data.Name})
}
render() {
return (
Welcome to Dashboard
Welcome :{this.state.name}
{/*
*/}
) } } 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
".
CREATE TABLE [dbo].[Socaillogin](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Email] [varchar](50) NULL,
[ProviderName] [varchar](50) NULL,
[Image] [varchar](650) NULL,
[Token] [nvarchar](650) NULL,
CONSTRAINT [PK_Socaillogin] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, _
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Create a Web API Project
Now open Visual Studio and create a new project.
Change the name as LoginApplication
.
Choose the template as Web API.
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 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.
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
public class Userdetails
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string ProviderName { get; set; }
public string Image { get; set; }
public string Token { get; set; }
}
Response Class
public class Response
{
public string Status { set; get; }
public string Message { set; get; }
}
Right-click on the Controllers folder and add a new controller. Name it as "Login controller" and add the following namespace:
using LoginWithSocialMedio.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 LoginWithSocialMedio.Models;
namespace LoginWithSocialMedio.Controllers
{
[RoutePrefix("Api/Login")]
public class LoginController : ApiController
{
[Route("SocialmediaData")]
[HttpPost]
public object SocialmediaData(Userdetails user)
{
try
{
DemoTestEntities DB = new DemoTestEntities();
Socaillogin Social = new Socaillogin();
if (Social.Id == 0)
{
Social.Name = user.Name;
Social.Email = user.Email;
Social.ProviderName = user.ProviderName;
Social.Image = user.Image;
Social.Token = user.Token;
var res = DB.Socaillogins.Add(Social);
DB.SaveChanges();
return res;
}
}
catch (Exception)
{
throw;
}
return new Response
{ Status = "Error", Message = "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 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.
History
- 20th February, 2020: Initial version