gpt4 book ai didi

c# - 无法从 Google OAuth2 token 端点获取访问 token

转载 作者:行者123 更新时间:2023-11-30 18:27:03 24 4
gpt4 key购买 nike

我正在尝试从 Google 的授权端点检索访问 token ,但我一直收到 401:未授权

我非常确定发送的所有值(授权代码、客户端 ID、客户端密码、重定向 uri 和授权类型)都是正确的。

我的代码如下:

using (HttpClient client = new HttpClient()) {
IEnumerable<KeyValuePair<string,string>> data = new List<KeyValuePair<string,string>>
{
new KeyValuePair<string,string>("code", "CODE_HERE"),
new KeyValuePair<string,string>("client_id", "CLIENT_ID_HERE"),
new KeyValuePair<string,string>("client_secret", "CLIENT_SECRET_HERE"),
new KeyValuePair<string,string>("redirect_uri", "REDIRECT_URI_HERE"),
new KeyValuePair<string,string>("grant_type", "authorization_code"),
}

HttpContent content = new FormUrlEncodedContent(data);

/* I'm getting 401 Unauthorized */
HttpResponseMessage response = await client.PostAsync("https://www.googleapis.com/oauth2/v3/token", content);
}

响应的 JSON 是:

{
"error": "invalid_client",
"error_description": "Unauthorized"
}

但是,我是从我的 Google Developer 控制面板复制并粘贴客户的 ID 和客户的密码,所以它们不可能是错误的。

有什么帮助吗?

最佳答案

这是对我有用的。在此示例中,我使用 RefreshToken 获取 AccessToken。

var client_id = ConfigurationManager.AppSettings.Get("GoogleClientId");
var client_secret = ConfigurationManager.AppSettings.Get("GoogleSecret");
var grant_type = "refresh_token";

var url = "https://www.googleapis.com/oauth2/v4/token";

IEnumerable<KeyValuePair<string, string>> data = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("client_id", client_id),
new KeyValuePair<string,string>("client_secret", client_secret),
new KeyValuePair<string,string>("grant_type", grant_type),
new KeyValuePair<string,string>("refresh_token", refreshToken),
};

var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

HttpContent contentPost = new FormUrlEncodedContent(data);

HttpResponseMessage response = await client.PostAsync(url, contentPost);
var result = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<GoogleAPIAuth>(result);

这是我的 GoogleAPIAuth 类。

public class GoogleAPIAuth
{
public string client_secret { get; set; }
public string grant_type { get; set; }
public string refresh_token { get; set; }
public string client_id { get; set; }
public string access_token { get; set; }
public string expires_in { get; set; }
public string token_type { get; set; }
}

关于c# - 无法从 Google OAuth2 token 端点获取访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27451047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com