React Google Login
A Google oAUth Sign-in / Log-in Component for React
Storybook
Install
npm install react-google-login
How to use
import React from 'react';
import ReactDOM from 'react-dom';
import GoogleLogin from 'react-google-login';
// or
import { GoogleLogin } from 'react-google-login';
const responseGoogle = (response) => {
console.log(response);
}
ReactDOM.render(
<GoogleLogin
clientId="658977310896-knrl3gka66fldh83dao2rhgbblmd4un9.apps.googleusercontent.com"
buttonText="Login"
onSuccess={responseGoogle}
onFailure={responseGoogle}
cookiePolicy={'single_host_origin'}
/>,
document.getElementById('googleButton')
);
Google button without styling or custom button
ReactDOM.render(
<GoogleLogin
clientId="658977310896-knrl3gka66fldh83dao2rhgbblmd4un9.apps.googleusercontent.com"
render={renderProps => (
<button onClick={renderProps.onClick} disabled={renderProps.disabled}>This is my custom Google button</button>
)}
buttonText="Login"
onSuccess={responseGoogle}
onFailure={responseGoogle}
cookiePolicy={'single_host_origin'}
/>,
document.getElementById('googleButton')
);
Login Hook
import { useGoogleLogin } from 'react-google-login'
const { signIn, loaded } = useGoogleLogin({
onSuccess,
clientId,
cookiePolicy,
loginHint,
hostedDomain,
autoLoad,
isSignedIn,
fetchBasicProfile,
redirectUri,
discoveryDocs,
onFailure,
uxMode,
scope,
accessType,
responseType,
jsSrc,
onRequest,
prompt
})
Logout Hook
import { useGoogleLogout } from 'react-google-login'
const { signOut, loaded } = useGoogleLogout({
jsSrc,
onFailure,
clientId,
cookiePolicy,
loginHint,
hostedDomain,
fetchBasicProfile,
discoveryDocs,
uxMode,
redirectUri,
scope,
accessType,
onLogoutSuccess
})
onSuccess callback
If responseType is not 'code', callback will return the GoogleAuth object.
If responseType is 'code', callback will return the offline token for use on your server.
If you use the hostedDomain param, make sure to validate the id_token (a JSON web token) returned by Google on your backend server:
- In the
responseGoogle(response) {...}
callback function, you should get back a standard JWT located atresponse.tokenId
orres.getAuthResponse().id_token
- Send this token to your server (preferably as an
Authorization
header) - Have your server decode the id_token by using a common JWT library such as jwt-simple or by sending a GET request to
https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=YOUR_TOKEN_HERE
- The returned decoded token should have an
hd
key equal to the hosted domain you'd like to restrict to.
Logout
Use GoogleLogout button to logout the user from google.
import { GoogleLogout } from 'react-google-login';
<GoogleLogout
clientId="658977310896-knrl3gka66fldh83dao2rhgbblmd4un9.apps.googleusercontent.com"
buttonText="Logout"
onLogoutSuccess={logout}
>
</GoogleLogout>