9

I've implemented login with google functionality for my login page and I've used @react-oauth/google package. And in my app to dispatch the login action I need 4 things - name, email, token & googleId.
Previously I had used react-google-login package and there I was getting all these items. But from current package docs I found...

import { GoogleLogin } from '@react-oauth/google';

<GoogleLogin
  onSuccess={credentialResponse => {
    console.log(credentialResponse);
  }}
  onError={() => {
    console.log('Login Failed');
  }}
/>;

From the response I'm getting name and email but there's no googleID or token which is required. Below is my dispatch function

  const googleSuccess = (resp) => {
    let decoded = jwt_decode(resp?.credential);
    const email = decoded?.email;
    const name = decoded?.name;
    const token = resp?.tokenId;
    const googleId = resp?.googleId;
    const result = { email, name, token, googleId };
    dispatch(googleLogin({ result, navigate, toast }));
    console.log(result);
  };

I had to use jwt-decode as the response I was getting was a JWT token.
And this is the Button component

       <GoogleLogin
          onSuccess={(resp)=>googleSuccess(resp)}
          onError={() => {
            console.log("Login Failed");
          }}
        />

I checked other ways like

import { useGoogleLogin } from '@react-oauth/google';

const login = useGoogleLogin({
  onSuccess: tokenResponse => console.log(tokenResponse),
});

<MyCustomButton onClick={() => login()}>
  Sign in with Google 🚀{' '}
</MyCustomButton>;

but here I'm not getting name, email and googleID.

So Any suggestions?

2
  • Have done similar to you; need id_token to pass down to services; did you work it out?
    – 9swampy
    Commented Mar 13, 2023 at 20:04
  • @9swampy I had added flow: "auth-code", in onsuccess handler...but didn't get the expected output
    – buzz
    Commented Mar 14, 2023 at 4:47

4 Answers 4

9

You can get id_token (JWT) by using the personalised button for authentication.

useGoogleLogin hook is wrapping the Authorization part in new Google SDK

const googleLogin = useGoogleLogin({
onSuccess: async tokenResponse => {
  console.log(tokenResponse);
  // fetching userinfo can be done on the client or the server
  const userInfo = await axios
    .get('https://www.googleapis.com/oauth2/v3/userinfo', {
      headers: { Authorization: `Bearer ${tokenResponse.access_token}` },
    })
    .then(res => res.data);

  console.log(userInfo);
},
// flow: 'implicit', // implicit is the default

});

But my recommendation for you as you have a backend, go with Authorization code flow, which will return code that you will exchange with your backend to obtain because it is more secure way.

Here is the source of entire discussion with examples for auth-code flow for client-side and back-end as well: https://github.com/MomenSherif/react-oauth/issues/12

4
  • How can i get the idtoken with personalised button ? Commented Jul 31, 2023 at 15:10
  • @SudipShrestha you can find that in userInfo from code above
    – Arkady
    Commented Sep 1, 2023 at 14:10
  • 1
    It works for me! I was originally using the GoogleLogin component, why do they gives different return, why can't it just return the same thing like useGoogleLogin... I wonder
    – v.ng
    Commented Dec 30, 2023 at 16:46
  • @Arkady I'm not getting an ID token with the response from googleapis.com/oauth2/v3/userinfo, any idea why that would be excluded? other properties like email, picture, and sub are included.
    – DeonV
    Commented Feb 28 at 7:32
2

I have found this webpage which clears out many of questions related to the topic of Google's auth flow, specifically about standard Google button vs custom login button and respectively credential vs access_token response data.

1
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Oct 6, 2023 at 4:11
0

I encountered challenges in obtaining the access token directly from the Google Login button using a similar approach. However, I found success by utilizing the 'useGoogleLogin' hook provided by the '@react-oauth/google' library, which facilitated the retrieval of the access token

const login =  useGoogleLogin({
      onSuccess:token=>{
        console.log(token) // it will have the access token
      },
      onError:error=>{
        console.log(error)
      }
    })
  return (
        <Button startContent={<FcGoogle size={25} />} color='' onClick={login} > Sign in with Google</Button>
0

You could use this , it worked perfectly for me...

   const login = useGoogleLogin({
           onSuccess: async tokenResponse => {
               const token = tokenResponse.access_token;
             // fetching userinfo can be done on the client or the server
             const userInfo = await axios
               .get('https://www.googleapis.com/oauth2/v3/userinfo', 
                 { headers: { Authorization: `Bearer ${tokenResponse.access_token}` },
               })
             const result = userInfo.data;
            // contains name, email & googleId(sub)
           },
         });
2
  • It looks like you copied the code from the top voted answer and edited it a little bit
    – zoran404
    Commented Jan 2 at 13:01
  • The website has a big problem with duplicates, both questions and answers...
    – zoran404
    Commented Jan 3 at 22:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.