To request the access token you only need to do a request posting the authentication data. This code has been extracted from a working MVC app using the resource owner password credentials grant:
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;
}
I hope it helps.
EDIT
Here you have a code snippet refreshing the 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;
}
And using it:
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;
}