gpt4 book ai didi

c# - oAuth 2.0 API 使用 C#

转载 作者:太空宇宙 更新时间:2023-11-03 17:39:10 26 4
gpt4 key购买 nike

我们的客户需要将他们的 API 与我们为他们开发的网站集成。 API 身份验证是通过 oAuth 2.0 完成的。他们提供了所有必要的信息(客户端 ID、客户端密码、 token Uri 等)。

但是,我们很难理解通过 C# 调用它的代码片段。我们知道我们必须请求一个请求 token 并将其附加到后续请求的 header 中。我们尝试了 DotNetOpenAuth 和 Owin,但无法找到实现这个的实际代码/到目前为止没有成功。
任何人都可以用一小段 C# 代码来帮助我实现这一目标吗?

最佳答案

要请求访问 token ,您只需要发布身份验证数据的请求。此代码已使用资源所有者密码凭据授权从工作的 MVC 应用程序中提取:

using (var client = new HttpClient())
{
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("username", _user));
postData.Add(new KeyValuePair<string, string>("password", _pwd));
postData.Add(new KeyValuePair<string, string>("grant_type", "password"));
postData.Add(new KeyValuePair<string, string>("client_id", _clientId));
postData.Add(new KeyValuePair<string, string>("client_secret", _clientSecret));

HttpContent content = new FormUrlEncodedContent(postData);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

var responseResult = client.PostAsync(_tokenUrl, content).Result;

return responseResult.Content.ReadAsStringAsync().Result;
}

我希望它有所帮助。

编辑

这里有一个代码片段刷新 token :
using (var client = new HttpClient())
{
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("refresh_token", _refreshToken));
postData.Add(new KeyValuePair<string, string>("grant_type", "refresh_token"));
postData.Add(new KeyValuePair<string, string>("client_id", _clientId));
postData.Add(new KeyValuePair<string, string>("client_secret", _clientSecret));

HttpContent content = new FormUrlEncodedContent(postData);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

var responseResult = client.PostAsync(_tokenUrl, content).Result;

return responseResult.Content.ReadAsStringAsync().Result;
}

并使用它:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
HttpResponseMessage result = client.GetAsync(_url).Result;

if (result.StatusCode == HttpStatusCode.Unauthorized)
{
RefreshToken(); /* Or reenter resource owner credentials if refresh token is not implemented */
if (/* token refreshed, repeat the request using the new access token */)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _newAccessToken);

result = client.GetAsync(_url).Result;

if (result.StatusCode == HttpStatusCode.Unauthorized)
{
// Process the error
}
}
}

return result;
}

关于c# - oAuth 2.0 API 使用 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37934070/

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