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

.NET Blazor应用中Google OAuth令牌交换失败求助

Google OAuth授权码换令牌出现invalid_grant错误的排查与建议

可能的排查方向

  • 重定向URI严格匹配:Google Cloud控制台中配置的重定向URI必须和代码中的https://localhost:7155/gauth完全一致,包括协议(https)、端口、路径,不能有结尾斜杠或大小写差异。
  • 授权码不可重复使用:Google授权码仅能使用一次,哪怕之前交换失败,该码也会失效,需重新引导用户获取新的授权码再测试。
  • 排除DataStore干扰:尝试将ExchangeCodeForTokenAsync的userId参数传空字符串,确认是否是DataStore中存储的旧数据导致冲突。
  • 客户端凭据配置正确:确保在Google控制台创建的是Web应用类型的OAuth客户端ID,且ClientId和ClientSecret无复制错误(无多余空格、特殊字符)。

是否需要放弃官方库?

不建议直接自行编写API调用。Google .NET Auth库已经封装了令牌刷新、过期管理、签名验证等核心逻辑,自行实现容易遗漏安全细节或引入新问题。优先排查上述问题,若确认官方库存在无法解决的特定场景,再考虑直接调用API:

自行调用令牌交换API的示例逻辑(仅作参考):

using System.Net.Http;
using System.Text.Json;

var client = new HttpClient();
var requestData = new FormUrlEncodedContent(new Dictionary<string, string>
{
    ["code"] = authorizationCode,
    ["client_id"] = clientId,
    ["client_secret"] = clientSecret,
    ["redirect_uri"] = "https://localhost:7155/gauth",
    ["grant_type"] = "authorization_code"
});

var response = await client.PostAsync("https://oauth2.googleapis.com/token", requestData);
var responseContent = await response.Content.ReadAsStringAsync();
var tokenResult = JsonSerializer.Deserialize<Dictionary<string, object>>(responseContent);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 04:36:09