Google Token端点返回unsupported_grant_type错误的排查与解决
Google OAuth授权码兑换Token报错解决
问题
我正在实现Google OAuth功能,以获取使用Google登录用户的姓名、头像等信息。通过react-oauth库设置flow: 'auth_code'参数,已成功获取到授权code。随后将该code发送至后端,后端按Google OpenID文档要求向https://oauth2.googleapis.com/token端点发起请求,代码如下:
try { const resp = await axios.post("https://oauth2.googleapis.com/token", { code: googleJWT, client_id: getGoogleClientId(), client_secret: googleSecret, redirect_uri: "http://localhost:3000", grant_type: "authorization_code" }, { headers: { "Content-Type": "application/x-www-form-urlencoded" } }) console.log("################## posted", resp) } catch (e) { console.log("################## could not post") console.log(e) }
但请求返回错误:
error: 'unsupported_grant_type', error_description: 'Invalid grant_type: '
尽管Discovery文档显示authorization_code为支持的授权类型,请求的Axios配置中data为JSON格式,却设置了Content-Type: application/x-www-form-urlencoded。请问为何Google提示授权类型不支持?如何将code兑换为ID Token?
解决方法
错误原因
你指定了Content-Type: application/x-www-form-urlencoded请求头,但发送的请求体是JSON格式,Google的Token端点无法正确解析参数,导致识别不到grant_type字段,因此返回unsupported_grant_type错误。
修正步骤
- 转换请求体为表单编码格式
Axios默认会将JSON对象序列化为JSON字符串发送,当你设置表单编码的Content-Type时,需要手动把参数转换成URL编码的表单格式。可以使用URLSearchParams来处理:try { const params = new URLSearchParams(); params.append('code', googleJWT); params.append('client_id', getGoogleClientId()); params.append('client_secret', googleSecret); params.append('redirect_uri', 'http://localhost:3000'); params.append('grant_type', 'authorization_code'); const resp = await axios.post("https://oauth2.googleapis.com/token", params, { headers: { "Content-Type": "application/x-www-form-urlencoded" } }) console.log("################## posted", resp) } catch (e) { console.log("################## could not post") console.log(e) } - 获取并解析ID Token
成功请求后,响应数据中会包含id_token字段,这是一个JWT格式的令牌。你可以直接解析这个令牌,从中提取用户的姓名、头像、邮箱等基本信息,无需额外调用用户信息接口。
内容的提问来源于stack exchange,提问作者Paymahn Moghadasian
相关产品推荐
相关产品推荐

