交换刷新和访问令牌 OAuth2 的授权代码

Exchanging authorization code for refresh and access tokens OAuth2

我正在尝试交换我在 this step of the documentation for refresh and access tokens. Where I'm stuck is how to send a request for the Json that contains the access and refresh tokens as described here 中获得的授权码。

这是我的代码:

string paras = string.Format("code={0}&client_id={1}&client_secret={2}&grant_type={4}&redirect_uri={3}",
    AuthCode,
    ClientID,
    ClientSecret,
    "urn:ietf:wg:oauth:2.0:oob",
    "authorization_code"
);
var req = WebRequest.Create("https://www.googleapis.com/oauth2/v4/token/") as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] data = Encoding.UTF8.GetBytes(paras);
req.ContentLength = data.Length;
using (Stream stream = req.GetRequestStream())
    stream.Write(data, 0, data.Length);
req.GetResponse();

System.Net.WebException: 'The remote server returned an error: (400) Bad Request.' 被扔到 req.GetResponse();

我的两个理论是我需要在开发者控制台中添加一个重定向 uri 并使用它,或者添加一个代码验证器。

当向 https://accounts.google.com/o/oauth2/v2/auth 发出请求以启动 OAuth2 流程并获取授权代码 (OAuth 2.0 Step 2) 时,redirect_uri 参数接受特殊的 urn:ietf:wg:oauth:2.0:oob URI 以指定获取响应的手动 copy/paste。

但是,在 OAuth 2.0 Step 5(为刷新和访问令牌交换授权代码)中,redirect_uri 参数 接受上述 URI,因此您将必须使用已在您的 GCP 项目中设置的有效 URI(您可以通过转到凭据>您的凭据>授权重定向 URI 添加一个)。

此外,为了调试 API 返回的响应错误,我建议您查看 this link,它描述了如何获取和打印与失败请求一起返回的信息。

redirect_uri 必须与 when the authorization code was requested 相同。

我也错过了this stepcode_challenge 可以与 code_verifier 相同,但前提是 code_challenge_methodplain。文档说它只是 "recommended" 请求授权代码,而实际上稍后需要它。