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控制台创建的项目客户端IDclient_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
相关产品推荐
相关产品推荐

