public string ExchangeAuthorizationCodeForAccessToken(string code)
{
var uri =
"{0}/auth/token".FormatWith(HostName);
var data =
"grant_type=authorization_code" +
"&code={0}".FormatWith(code) +
"&client_id={0}".FormatWith(ClientID) +
"&client_secret={0}".FormatWith(ClientSecret) +
"&redirect_uri={0}".FormatWith(RedirectUri);
var req = (HttpWebRequest)WebRequest.Create(uri);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
var bytes = System.Text.Encoding.ASCII.GetBytes(data);
req.ContentLength = bytes.Length;
using (var os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
using (var resp = req.GetResponse())
{
using (var reader = new StreamReader(resp.GetResponseStream()))
{
var anonType = new { access_token = string.Empty, token_type = string.Empty, expires_in = 0, scope = string.Empty };
return JsonConvert.DeserializeAnonymousType(reader.ReadToEnd(), anonType).access_token;
}
}
}