如何在@react-oauth/google中获取token与Google ID?
@react-oauth/google 获取登录所需参数的解决办法
一、使用GoogleLogin组件的方案
GoogleLogin组件返回的credential字段本身就是JWT格式的token,而googleId可以通过解析该JWT的sub字段获取(Google的JWT中sub对应用户唯一ID)。结合jwt-decode即可拿到全部所需参数:
import { GoogleLogin } from '@react-oauth/google'; import jwtDecode from 'jwt-decode'; // 组件内使用 <GoogleLogin onSuccess={(response) => { const { credential } = response; const decodedUser = jwtDecode(credential); // 组装登录所需参数 const loginData = { name: decodedUser.name, email: decodedUser.email, token: credential, // credential即为所需的token googleId: decodedUser.sub // sub字段对应googleId }; // 分发登录动作 dispatch(yourLoginAction(loginData)); }} onError={() => console.error('谷歌登录失败')} />
二、使用useGoogleLogin钩子的方案
使用useGoogleLogin时,需要指定scope权限获取用户信息,再通过Google的用户信息API拉取name、email和googleId,同时response.access_token就是所需的token:
import { useGoogleLogin } from '@react-oauth/google'; const LoginComponent = () => { const handleGoogleLogin = useGoogleLogin({ scope: 'openid email profile', // 必须声明该权限才能获取用户基本信息 onSuccess: async (response) => { // 调用Google用户信息API获取详细数据 const userInfoRes = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', { headers: { Authorization: `Bearer ${response.access_token}` } }); const userInfo = await userInfoRes.json(); // 组装登录参数 const loginData = { name: userInfo.name, email: userInfo.email, token: response.access_token, googleId: userInfo.sub }; // 分发登录动作 dispatch(yourLoginAction(loginData)); }, onError: () => console.error('谷歌登录失败') }); return <button onClick={handleGoogleLogin}>谷歌登录</button>; };
额外注意事项
- 确保Google Cloud Console中你的OAuth 2.0客户端ID已正确配置,并且启用了必要的API(如OAuth2 API)。
- 若遇到权限不足的问题,检查Google Cloud Console中已授权的scope是否包含
openid、email、profile。
内容的提问来源于stack exchange,提问作者buzz
相关产品推荐
相关产品推荐

