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

Google Token Auth API始终返回Bad Request错误的排查与解决

Google OAuth2获取Token时400 Bad Request问题排查与解决

我按照Google官方文档实现Web请求,让用户通过Google Authentication访问WebApp,但在第二步获取认证token时遇到问题——第一步获取到code参数后,调用token接口始终返回400 Bad Request错误。

使用的URI

  • 获取code的URI:https://accounts.google.com/o/oauth2/auth
  • Token接口URI:https://oauth2.googleapis.com/token

实现代码

var requestCode = Request.Query["code"].ToString();

var httpClient = new HttpClient();

var body = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("client_id", _googleSettings.ClientId),
    new KeyValuePair<string, string>("client_secret", _googleSettings.ClientSecret),
    new KeyValuePair<string, string>("redirect_uri", _googleSettings.RedirectUris[1]),
    new KeyValuePair<string, string>("grant_type", "authorization_code"),
    new KeyValuePair<string, string>("code", requestCode),
};

var content = new FormUrlEncodedContent(body);

var response = await httpClient.PostAsync(_googleSettings.TokenUri, content);

响应详情

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
  Date: Wed, 09 Aug 2023 20:25:03 GMT
  Cache-Control: no-cache, no-store, max-age=0, must-revalidate
  Pragma: no-cache
  Vary: X-Origin
  Vary: Referer
  Vary: Origin,Accept-Encoding
  Server: scaffolding on HTTPServer2
  X-XSS-Protection: 0
  X-Frame-Options: SAMEORIGIN
  X-Content-Type-Options: nosniff
  Alt-Svc: h3=":443"; ma=2592000
  Alt-Svc: h3-29=":443"; ma=2592000
  Accept-Ranges: none
  Transfer-Encoding: chunked
  Expires: Mon, 01 Jan 1990 00:00:00 GMT
  Content-Type: application/json; charset=utf-8
}}

解决方案
我在Google应用中配置了两个回调URI,但Google无法识别列表中的第二个URI(返回Bad Request错误)。切换使用第一个注册的重定向URI后,问题解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 20:22:32