My *_*per 1 c# asp.net-mvc oauth-2.0 asp.net-web-api
我们的客户要求将他们的API与我们为他们开发的网站集成.API身份验证是通过oAuth 2.0完成的.他们提供了所有必要的信息(客户ID,客户端密钥,令牌Uri等).
但是我们很难理解代码片段通过C#调用它.我们知道我们必须请求一个请求令牌并将其附加到头部以便后续请求.我们尝试了DotNetOpenAuth和Owin,但无法找到实现此实际代码/到目前为止没有成功.任何人都可以通过一小段C#代码来帮助我实现这一目标吗?
jum*_*uro 10
要请求访问令牌,您只需要发送身份验证数据的请求.此代码已使用资源所有者密码凭据grant从工作的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;
}
Run Code Online (Sandbox Code Playgroud)
我希望它有所帮助.
编辑
这里有一个代码片段来刷新令牌:
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;
}
Run Code Online (Sandbox Code Playgroud)
并使用它:
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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4222 次 |
最近记录: |