Last active
December 27, 2022 09:44
-
-
Save toluolatubosun/de46263f5fbe3ce8656411d2204e6591 to your computer and use it in GitHub Desktop.
Authenticate users with the new Google Identity Service (GSI) - React Frontend - Node.JS Backend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Backend with Node.JS | |
import { OAuth2Client } from "google-auth-library"; | |
const googleAuthentication = async (response: any) => { | |
const { credential } = response; | |
const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID); | |
const ticket = await client.verifyIdToken({ | |
idToken: credential, | |
audience: process.env.GOOGLE_CLIENT_ID | |
}); | |
const userInfo = ticket.getPayload(); | |
if (userInfo) { | |
const { email, picture, given_name, family_name, sub } = userInfo; | |
} | |
// Save user info to database | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Frontend with React | |
import React from "react"; | |
declare global { | |
interface Window { | |
GoogleAuthSuccess?: any; | |
} | |
} | |
const GoogleAuthentication = () => { | |
// Handle success | |
const GoogleAuthSuccess = (response: any) => { | |
console.log("Success", response); | |
// send the respone to your backend, or decoded the JWT "credential" | |
}; | |
// Set the global function | |
if (typeof window !== "undefined") { | |
window.GoogleAuthSuccess = GoogleAuthSuccess; | |
} | |
// Load Script | |
const scriptRef = React.useRef<HTMLDivElement>(null); | |
React.useEffect(() => { | |
const script = document.createElement("script"); | |
script.src = "https://accounts.google.com/gsi/client"; | |
script.async = true; | |
script.defer = true; | |
if (scriptRef.current) { | |
scriptRef.current.appendChild(script); | |
} | |
return () => { | |
scriptRef.current?.removeChild(script); | |
}; | |
}, [scriptRef]); | |
return ( | |
<> | |
<div ref={scriptRef}></div> | |
{/* Configuration */} | |
<div | |
id="g_id_onload" | |
data-auto_prompt="false" | |
data-text="Continue with google" | |
data-callback="GoogleAuthSuccess" | |
data-client_id={process.env.GOOGLE_CLIENT_ID} | |
></div> | |
{/* Render Button */} | |
<div | |
data-size="large" | |
data-type="standard" | |
data-theme="outline" | |
className="g_id_signin" | |
data-shape="rectangular" | |
data-text="continue_with" | |
data-logo_alignment="center" | |
></div> | |
</> | |
); | |
}; | |
export default GoogleAuthentication; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment