在 @react-oauth/google 中获取令牌和 google id

buz*_*uzz 5 reactjs google-signin

我已经为我的登录页面实现了使用 google 功能登录,并且使用了 package.json @react-oauth/google。在我的应用程序中,要调度登录操作,我需要 4 件事 - 姓名、电子邮件、令牌和 googleId。
以前我使用过react-google-login包裹,在那里我得到了所有这些物品。但从当前的包文档我发现......

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

<GoogleLogin
  onSuccess={credentialResponse => {
    console.log(credentialResponse);
  }}
  onError={() => {
    console.log('Login Failed');
  }}
/>;
Run Code Online (Sandbox Code Playgroud)

从回复中我得到了姓名和电子邮件,但没有需要的 googleID 或令牌。下面是我的调度函数

  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);
  };
Run Code Online (Sandbox Code Playgroud)

我必须使用jwt-decode,因为我收到的响应是 JWT 令牌。
这是按钮组件

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

我检查了其他方式,比如

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

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

<MyCustomButton onClick={() => login()}>
  Sign in with Google {' '}
</MyCustomButton>;
Run Code Online (Sandbox Code Playgroud)

但在这里我没有得到姓名、电子邮件和 googleID。

那么有什么建议吗?

Ark*_*ady 7

您可以通过个性化按钮获取id_token(JWT)进行认证。

useGoogleLoginhook 将授权部分包装在新的 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
Run Code Online (Sandbox Code Playgroud)

});

但我建议您,因为您有后端,请使用授权代码流,它将返回您将与后端交换以获得的代码,因为这是更安全的方式。

以下是整个讨论的来源,以及auth-code客户端和后端流程的示例:https://github.com/MomenSherif/react-oauth/issues/12