BUY FULL SOURCE CODE
Welcome folks today in this blog post we will be implementing google identity services oauth2 login and logout
system in react.js application. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new react.js
application using the below command
npm create vite@ oauth2
cd oauth2
And after that you need to make a new react.js
application as shown below
Now we need to install the below libraries
using the below command as shown below
npm i jwt-decode
And now we need to include the cdn
inside the index.html
file as shown below
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite + React</title> <script src="https://accounts.google.com/gsi/client" async defer></script> </head> <body> <div id="root"></div> <script type="module" src="/src/main.jsx"></script> </body> </html> |
And now we need to make a App.jsx
file and copy paste the following code
App.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
import { useEffect, useState } from "react"; import "./App.css"; import jwt_decode from "jwt-decode"; function App() { const [user, setUser] = useState({}); let handleCallbackResponse = (response) => { console.log(response.credential); let userObject = jwt_decode(response.credential); setUser(userObject); document.getElementById('signInDiv').hidden = true }; useEffect(() => { google.accounts.id.initialize({ client_id:"##replaceyourownclientid##", callback: handleCallbackResponse, }); google.accounts.id.renderButton(document.getElementById("signInDiv"), { theme: "outline", size: "large", }); google.accounts.id.prompt() }, []); let handleLogout = (e) => { setUser({}) document.getElementById('signInDiv').hidden = false } return ( <div className="App"> <div id="signInDiv"></div> {Object.keys(user).length != 0 && <button onClick={handleLogout}>Sign Out</button> } {user && ( <div> <h1>{user.name}</h1> <img src={user.picture} /> </div> )} </div> ); } export default App; |
As you can see you need to go to cloud
console and then we need to generate the client_id
and then you need to replace it as shown above. And then it will return the jwt
token and then we will be decoding the token using the jwt-decode
library. And then we are showing the user
information. And also we have the logout
button where user will be able to logout from the system.
BUY FULL SOURCE CODE