使用@react-oauth/google获取access_token后,如何获取用户name、googleId等信息?
解决方法
你可以通过两种方式获取用户的name、googleId和imageUrl信息,以下是具体实现:
方案1:调用谷歌用户信息API获取数据
利用拿到的access_token向谷歌官方的用户信息端点发送请求,直接获取完整的用户数据:
import {useGoogleLogin} from '@react-oauth/google' import { useNavigate } from "react-router-dom" import {FcGoogle} from "react-icons/fc" import shareVideo from "../assets/share.mp4" import logo from "../assets/logowhite.png" import { jwtDecode } from "jwt-decode"; export default function Login(){ const navigate = useNavigate(); const login = useGoogleLogin({ onSuccess: async (tokenResponse) =>{ // 调用谷歌用户信息API const userInfo = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', { headers: { Authorization: `Bearer ${tokenResponse.access_token}` } }).then(res => res.json()); // 提取所需数据 const { name, sub: googleId, picture: imageUrl } = userInfo; console.log('用户信息:', { name, googleId, imageUrl }); // 可将数据存入本地存储或发送到后端 localStorage.setItem('user', JSON.stringify({ name, googleId, imageUrl })); // 示例:跳转到首页 navigate('/'); }, onError: (error) => console.log('登录失败:', error) }) return ( <> <div className= "flex justify-start items-center flex-col h-screen"> <div className="relative w-full h-full"> <video src={shareVideo} type="video/mp4" loop controls={false} muted autoPlay className="w-full h-full object-cover" /> <div className="absolute flex justify-center items-center top-0 right-0 left-0 bottom-0 bg-blackOverlay"> <div className="p-5"> <img src={logo} width="130px" alt="logo" className="logo-image"/> <div className="shadow-2xl"> {/* 修正原代码中ce拼写错误为className */} <button type="button" className="bg-mainColor flex justify-center items-center p-3 rounded-lg cursor-pointer outline-none" onClick={()=>login()} > <FcGoogle className="mr-4"/> Sign in with Google </button> </div> </div> </div> </div> </div> </> ) }
API返回的核心数据结构:
{ "sub": "1234567890", // 对应googleId "name": "用户全名", "picture": "https://lh3.googleusercontent.com/...", // 对应imageUrl "email": "用户邮箱" }
方案2:获取id_token并解码(无需额外API请求)
在登录配置中指定返回id_token,直接通过jwtDecode解码本地令牌获取数据,无需额外网络请求:
import {useGoogleLogin} from '@react-oauth/google' import { useNavigate } from "react-router-dom" import {FcGoogle} from "react-icons/fc" import shareVideo from "../assets/share.mp4" import logo from "../assets/logowhite.png" import { jwtDecode } from "jwt-decode"; export default function Login(){ const navigate = useNavigate(); const login = useGoogleLogin({ responseType: 'id_token token', // 添加该配置以获取id_token onSuccess: (tokenResponse) =>{ // 解码id_token得到用户信息 const decodedToken = jwtDecode(tokenResponse.id_token); // 提取所需数据 const { name, sub: googleId, picture: imageUrl } = decodedToken; console.log('用户信息:', { name, googleId, imageUrl }); // 后续数据存储或页面跳转逻辑 localStorage.setItem('user', JSON.stringify({ name, googleId, imageUrl })); navigate('/'); }, onError: (error) => console.log('登录失败:', error) }) return ( <> <div className= "flex justify-start items-center flex-col h-screen"> <div className="relative w-full h-full"> <video src={shareVideo} type="video/mp4" loop controls={false} muted autoPlay className="w-full h-full object-cover" /> <div className="absolute flex justify-center items-center top-0 right-0 left-0 bottom-0 bg-blackOverlay"> <div className="p-5"> <img src={logo} width="130px" alt="logo" className="logo-image"/> <div className="shadow-2xl"> {/* 修正原代码拼写错误 */} <button type="button" className="bg-mainColor flex justify-center items-center p-3 rounded-lg cursor-pointer outline-none" onClick={()=>login()} > <FcGoogle className="mr-4"/> Sign in with Google </button> </div> </div> </div> </div> </div> </> ) }
注:原代码中<div ce="shadow-2xl">存在拼写错误,需改为<div className="shadow-2xl">才能生效样式。
内容的提问来源于stack exchange,提问作者Rifat Al Emam Shoron
相关产品推荐
相关产品推荐

