Here’s the c# code that’s not working (secret keys withheld, guidState is a guid):
String strAuthFormat = "OAuth oauth_callback=\"{0}\", " +
"oauth_consumer_key=\"{1}\", " +
"oauth_nonce=\"{2}\", " +
"oauth_signature=\"{3}\", " +
"oauth_signature_method=\"{4}\", " +
"oauth_timestamp=\"{5}\", " +
"oauth_version=\"{6}\"";
String strBaseFormat = "OAuth oauth_callback={0}&" +
"oauth_consumer_key={1}&" +
"oauth_nonce={2}&" +
"oauth_signature_method={3}&" +
"oauth_timestamp={4}&" +
"oauth_version={5}";
String strURL = strSecureUrl + "ExternalAuthentication.aspx?site=twitter";
String strRedirect = "https://api.twitter.com/oauth/request_token";
String strClientID = "The Consumer Key";
String strClientSecret = "The Consumer Secret";
String strSignKey = "";
strSignKey = Uri.EscapeDataString(strClientID) + "&" +Uri.EscapeDataString(strClientSecret);
var Timestamp = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var oauth_Timestamp = Convert.ToInt64(Timestamp.TotalSeconds).ToString();
String strBaseString = String.Format(strBaseFormat,
strURL,
strClientID,
guidState.ToString().Replace("-",""),
"HMAC-SHA1",
oauth_Timestamp,
"1.1");
strBaseString = string.Concat("POST&", Uri.EscapeDataString(strRedirect), "&", Uri.EscapeDataString(strBaseString));
String strSignature = "";
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(strSignKey)))
{
strSignature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strBaseString)));
}
String strAuthHeader = string.Format(strAuthFormat,
strURL,
strClientID,
guidState.ToString().Replace("-",""),
strSignature,
"HMAC-SHA1",
oauth_Timestamp,
"1.1");
ServicePointManager.Expect100Continue = false;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(strRedirect);
objRequest.Headers.Add("Authorization", strAuthHeader);
objRequest.Method = "POST";
objRequest.ContentType = "application/x-www-form-urlencoded";
using (Stream objStream = objRequest.GetRequestStream())
{
byte[] objContent = ASCIIEncoding.ASCII.GetBytes("");
objStream.Write(objContent, 0, 0);
}
WebResponse objResponse = null;
try
{
objResponse = objRequest.GetResponse();
objResponse.Close();
}
catch (WebException e)
{
Response.Write(e.Message);
var objErrResponse = (WebResponse)e.Response;
StreamReader objSR = new StreamReader(objErrResponse.GetResponseStream());
String strResponse = objSR.ReadToEnd();
Response.Write("<br/>" + strResponse);
}
The header generated is (with XXXXXX’s overwritten on part of the key and signature):
OAuth oauth_callback=“https%3A%2F%2Fdev.oursite.com%2Fsecure%2FExternalAuthentication.aspx%3Fsite%3Dtwitter”,oauth_consumer_key=“qqGXXXXXXXXXxFg”,oauth_nonce=“19b37a1aa13b43b58691dfd484cf3ad7”,oauth_signature_method=“HMAC-SHA1”,oauth_timestamp=“1421182206”,oauth_version=“1.1”,oauth_signature=“wZ2zGGtXXXXXXXX1Ttg=”
Any clues what’s wrong?
–Owen