Blazor WASM+ASP.NET Web API获取Google OAuth令牌遇400错误求助
解决Blazor WASM+ASP.NET Web API Google认证获取Token 400错误的排查步骤
核心问题排查方向
- 授权码有效性问题:Google授权码仅能使用一次,若你之前尝试过用该码请求Token,会直接返回400。请重新获取新的授权码再尝试。
- 重定向URI完全匹配:登录Google Cloud控制台,检查OAuth 2.0客户端ID配置里的「已授权的重定向URI」,必须和代码中
redirectUri的每一个字符完全一致,包括https/http、端口号、路径,甚至大小写都不能错。 - Client ID/Secret准确性:确认
configuration中读取的Authentication:Google:ClientId和ClientSecret与Google Cloud控制台里的完全一致,注意不要包含多余的空格或换行符。 - 客户端应用类型适配:Blazor WASM属于纯客户端SPA应用,Google要求这类应用使用PKCE流程,而非直接携带
client_secret(客户端无法安全存储密钥,Google会拒绝此方式的请求)。你需要调整实现逻辑:- 在获取授权码时,生成随机的
code_verifier和对应的code_challenge,并将code_challenge和code_challenge_method=S256附加到授权请求中。 - 在请求Token时,携带
code_verifier参数,移除client_secret参数。
- 在获取授权码时,生成随机的
调整后的请求示例(适配PKCE)
// 注意:code_verifier需要是你在获取授权码时生成的那个随机字符串 var codeVerifier = "你的code_verifier字符串"; var authCode = "新获取的授权码"; var clientId = configuration.GetValue<string>("Authentication:Google:ClientId") ?? string.Empty; var redirectUri = "https://localhost:7210/authentication/login-callback"; var tokenUri = "https://oauth2.googleapis.com/token"; var parameters = new Dictionary<string, string> { { "code", authCode }, { "client_id", clientId }, { "redirect_uri", redirectUri }, { "grant_type", "authorization_code" }, { "code_verifier", codeVerifier } // 添加PKCE的code_verifier,移除client_secret }; var content = new FormUrlEncodedContent(parameters); var httpClient = httpClientFactory.CreateClient(); var response = await httpClient.PostAsync(tokenUri, content); // 建议添加响应内容读取,查看具体错误信息 if (!response.IsSuccessStatusCode) { var errorContent = await response.Content.ReadAsStringAsync(); // 打印或记录errorContent,Google会返回详细错误原因,比如"invalid_grant"等 }
额外建议
请求失败时一定要读取响应的内容,Google会返回具体的错误描述(比如"error": "invalid_grant","error_description": "Code was already used."),这能快速定位问题。
内容的提问来源于stack exchange,提问作者Kazuki
相关产品推荐
相关产品推荐

