You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Google Login获取Token ID?遇JsonWebTokenError: jwt malformed错误

解决@react-oauth/google登录时jwt malformed错误及提取ID Token的方法

错误原因分析

你遇到的JsonWebTokenError: jwt malformed错误,大概率是以下两种情况:

  • res.credential为空或不是有效的JWT格式——可能是登录回调返回的结构不符合预期,或网络问题导致credential未正确获取。
  • 混淆了用户唯一标识(sub)和ID Token的概念:result.sub是谷歌用户的唯一ID,而你要的Token ID其实就是res.credential本身。

解决方案

1. 先验证res.credential的有效性

在解码前先打印完整的res对象,确认credential字段是否存在且是合法的三段式JWT字符串(格式为xxxx.yyyy.zzzz):

const googleSuccess = (res) => {
  console.log('完整返回结果:', res); // 先确认res的结构
  if (!res.credential) {
    console.log('未获取到有效的ID Token');
    return;
  }
  // 后续逻辑
};

2. 正确提取ID Token和用户信息

修正代码,直接将res.credential作为Token ID,解码后获取用户信息:

import jwtDecode from "jwt-decode";
import { GoogleLogin } from "@react-oauth/google";

// 登录组件
<GoogleLogin
  onSuccess={googleSuccess}
  onError={() => {
    console.log('Login Failed');
  }}
/>

const googleSuccess = (res) => {
  try {
    if (!res.credential) throw new Error('未获取到ID Token');
    
    // res.credential就是你要的Token ID
    const idToken = res.credential;
    // 解码获取用户信息
    const userInfo = jwtDecode(idToken);
    
    console.log('用户信息:', userInfo);
    console.log('Token ID:', idToken);
    
    dispatch({ type: AUTH, data: { result: userInfo, token: idToken } });
    navigateTo('/');
    
  } catch (error) {
    console.log('登录处理失败:', error);
  }
};

3. 额外注意事项

  • 确保jwt-decode包已正确安装:执行npm install jwt-decode或yarn add jwt-decode。
  • 如果仍报错,检查谷歌OAuth客户端ID是否配置正确,确保你的域名已加入谷歌开发者控制台的授权域名列表。

内容的提问来源于stack exchange,提问作者user16369468

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 04:35:00