要请求访问令牌,您只需要发布身份验证数据的请求。此代码已使用资源所有者密码凭据授权从工作 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;
}
希望对你有帮助。
编辑
这里有一段代码 sn-p 刷新令牌:
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;
}