Google OAuth刷新Access Token遇400错误:unsupported_grant_type求助
Google OAuth 刷新令牌 400 错误排查
问题分析
你遇到的400 Bad Request和"unsupported_grant_type"错误,核心由代码中的几个明显问题导致:
错误点修复
- client_secret 配置错误:代码里
client_secret误用了process.env.GOOGLE_AUTH_CLIENT_ID,这是复制时的低级错误,需替换为对应的客户端密钥环境变量process.env.GOOGLE_AUTH_CLIENT_SECRET。 - fetch 请求参数错误:
fetch配置项中不存在payload参数,正确参数名是body。- 由于设置了
Content-Type: application/x-www-form-urlencoded,不能直接传入JSON对象,必须将payload转换为URL编码字符串,可通过new URLSearchParams(payload).toString()实现。
修正后的代码
const URL = 'https://accounts.google.com/o/oauth2/token'; const headers = { 'Content-Type': 'application/x-www-form-urlencoded', }; const payload = { client_id: process.env.GOOGLE_AUTH_CLIENT_ID, client_secret: process.env.GOOGLE_AUTH_CLIENT_SECRET, // 修正客户端密钥 refresh_token: process.env.REFRESH_TOKEN, grant_type: 'refresh_token', }; console.log('payload', payload); // 修正fetch参数格式 const res = await fetch(URL, { method: 'post', headers, body: new URLSearchParams(payload).toString() }); console.log('res', res); const data = await res.text(); console.log('data', data);
额外检查项
- 确认
REFRESH_TOKEN有效,且对应的授权范围覆盖当前请求所需权限。 - 验证客户端ID、密钥与刷新令牌属于同一个Google OAuth应用。
- 检查环境变量是否正确加载,避免出现未定义值。
内容的提问来源于stack exchange,提问作者Pastilhas
相关产品推荐
相关产品推荐

