I’m working on adding twitter integration to a application of ours.
The issue I’m having is no matter what I do to try to get a token from the api it always come back as 401.
public string oAuthToken(string callbackUrl)
{
Uri oauthUrl = new Uri(REQUEST_TOKEN);
var oauthNonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture)));
var oauthTimestamp = this.GenerateTimeStamp();
var oauthSignature = "";
var authSignature = string.Format("oauth_callback={0}&oauth_consumer_key={1}&oauth_nonce={2}&oauth_signature_method={3}&oauth_timestamp={4}&oauth_token=xxxx&oauth_version={5}",
callbackUrl,
this.ConsumerKey,
oauthNonce,
OauthSignatureMethod,
oauthTimestamp,
OauthVersion);
var baseString = string.Format("POST&{0}&{1}", Uri.EscapeDataString(oauthUrl.AbsoluteUri), Uri.EscapeDataString(authSignature));
var compositeKey = string.Concat(Uri.EscapeDataString(this.ConsumerSecret), "&");
using (HMACSHA1 hasher = new HMACSHA1(Encoding.ASCII.GetBytes(compositeKey)))
{
oauthSignature = Convert.ToBase64String(hasher.ComputeHash(Encoding.ASCII.GetBytes(baseString)));
}
var authHeader = string.Format("OAuth oauth_consumer_key=\"{0}\", oauth_nonce=\"{1}\", oauth_signature=\"{2}\", oauth_signature_method=\"{3}\", oauth_timestamp=\"{4}\", oauth_token=\"xxxx\", oauth_version=\"{5}\"",
this.ConsumerKey,
oauthNonce,
oauthSignature,
OauthSignatureMethod,
oauthTimestamp,
OauthVersion);
ServicePointManager.Expect100Continue = false;
HttpWebRequest authRequest = (HttpWebRequest)System.Net.WebRequest.Create(oauthUrl);
authRequest.Method = "POST";
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Headers.Add("Accept-Encoding", "gzip");
authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
try
{
using (var response = authRequest.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception(String.Format("Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription));
}
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
return sr.ReadToEnd();
}
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
I also get this message returned to me:
Failed to validate oauth signature and token
Now I noticed that if I don’t try to set a callback url it will work, but I need to be able to set a custom callback url as our application has a custom url based on who is using the application.
Any help will be greatly appreciated.
Thx.