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

Google API‘兑换授权码’返回Unauthorized问题求助

Google OAuth2 令牌交换POST请求问题排查&示例

嘿,我看到你正在走Google OAuth2 Web Server流程的第5步,用C#构造POST请求来换取认证令牌。先把你给出的代码片段整理成规范的代码块:

List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>(); 
postData.Add(new KeyValuePair<string, string>("code", code)); 
postData.Add(new KeyValuePai...

从你没写完的代码来看,大概率是漏了Google要求的必填参数——这个接口有几个必须传的字段,少一个都会报错,我给你列出来:

  • client_id:你在Google Cloud控制台创建的项目客户端ID
  • client_secret:对应客户端的密钥,注意不要泄露
  • grant_type:固定填authorization_code,告诉Google你是用授权码换令牌
  • redirect_uri:必须和你之前获取授权码时用的跳转URI完全一致,差个斜杠或者大小写不同都不行

另外发送请求的时候还有几个容易踩坑的点:

  • 一定要把请求的Content-Type设置为application/x-www-form-urlencoded,不然Google无法正确解析你的参数
  • 请求地址要准确:https://oauth2.googleapis.com/token
  • 记得处理响应,尤其是错误情况——比如授权码过期会返回invalid_grant,参数不匹配会返回400错误

给你一个完整的可参考代码片段:

using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;

public async Task<string> ExchangeCodeForToken(string code)
{
    var postData = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("code", code),
        new KeyValuePair<string, string>("client_id", "你的客户端ID"),
        new KeyValuePair<string, string>("client_secret", "你的客户端密钥"),
        new KeyValuePair<string, string>("grant_type", "authorization_code"),
        new KeyValuePair<string, string>("redirect_uri", "你的跳转URI")
    };

    using var httpClient = new HttpClient();
    var formContent = new FormUrlEncodedContent(postData);
    var response = await httpClient.PostAsync("https://oauth2.googleapis.com/token", formContent);
    
    // 先检查响应状态码,抛出异常方便排查
    response.EnsureSuccessStatusCode();
    
    var responseBody = await response.Content.ReadAsStringAsync();
    return responseBody;
}

如果已经遇到了具体的错误(比如特定的HTTP状态码、返回的错误信息),可以把这些细节贴出来,这样能更快定位问题~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:24:03