请求访问令牌时 Twitter 请求令牌无效:C#
Twitter Invalid request token when requesting access token: C#
我正在尝试完成使用 Twitter 登录的第 3 步。将 OAuth 请求令牌交换为 OAuth 访问令牌。我在第 1 步中收到了一个访问令牌,用户可以在第 2 步中授权 returns a oauth_verifier。
我在这一步遇到的错误是 401 未经授权的访问:无效的请求令牌。
非常感谢对我做错了什么的一些见解。
public void Access_Token()
{
string oauthconsumerkey = ConfigurationManager.AppSettings["t_client_id"]; ;
string oauthconsumersecret = ConfigurationManager.AppSettings["t_client_secret"];
string oauthverifier = Request.QueryString["oauth_verifier"];
string oauthtokensecret = string.Empty;
string oauthtoken = Request.QueryString["oauth_token"];
string oauthsignaturemethod = "HMAC-SHA1";
string oauthversion = "1.0";
string oauthnonce = HttpUtility.UrlEncode(Guid.NewGuid().ToString("N"));
TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
string oauthtimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
string url = "https://api.twitter.com/oauth/access_token?oauth_verifier=" + Uri.EscapeDataString(oauthverifier);
SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
basestringParameters.Add("oauth_version", oauthversion);
basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
basestringParameters.Add("oauth_nonce", oauthnonce);
basestringParameters.Add("oauth_signature_method", oauthsignaturemethod);
basestringParameters.Add("oauth_timestamp", oauthtimestamp);
basestringParameters.Add("oauth_token", EncodeCharacters(oauthtoken));
//Build the signature string
StringBuilder baseString = new StringBuilder();
baseString.Append("POST" + "&");
baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split('?')[0]) + "&"));
foreach (KeyValuePair<string, string> entry in basestringParameters)
{
baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
}
//Remove the trailing ambersand char last 3 chars - %26
string finalBaseString = baseString.ToString().Substring(0, baseString.Length - 3);
//Build the signing key
string signingKey = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) + "&" +
EncodeCharacters(Uri.EscapeDataString(oauthtokensecret));
//Sign the request
HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
string oauthsignature = Convert.ToBase64String(
hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));
//Tell Twitter we don't do the 100 continue thing
ServicePointManager.Expect100Continue = false;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@url);
StringBuilder authorizationHeaderParams = new StringBuilder();
authorizationHeaderParams.Append("OAuth ");
authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauthconsumerkey) + "\",");
authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauthnonce) + "\",");
authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(oauthsignature) + "\",");
authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauthsignaturemethod) + "\",");
authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauthtimestamp) + "\",");
authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(oauthtoken) + "\"");
authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
webRequest.Headers.Add("Authorization", authorizationHeaderParams.ToString());
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
//Allow us a reasonable timeout in case Twitter's busy
webRequest.Timeout = 3 * 60 * 1000;
string responseFromServer;
try
{
//webRequest.Proxy = new WebProxy("enter proxy details/address");
HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
Stream dataStream = webResponse.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
responseFromServer = reader.ReadToEnd();
// responseFromServer; ;
}
catch (WebException e)
{
HttpWebResponse errorR = e.Response as HttpWebResponse;
Stream dataStream = errorR.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string dat = responseFromServer = reader.ReadToEnd();
}
您在下一行中忘记了一个逗号 (,)。
您的线路:
authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
应该是:
authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\",");
我正在尝试完成使用 Twitter 登录的第 3 步。将 OAuth 请求令牌交换为 OAuth 访问令牌。我在第 1 步中收到了一个访问令牌,用户可以在第 2 步中授权 returns a oauth_verifier。 我在这一步遇到的错误是 401 未经授权的访问:无效的请求令牌。
非常感谢对我做错了什么的一些见解。
public void Access_Token()
{
string oauthconsumerkey = ConfigurationManager.AppSettings["t_client_id"]; ;
string oauthconsumersecret = ConfigurationManager.AppSettings["t_client_secret"];
string oauthverifier = Request.QueryString["oauth_verifier"];
string oauthtokensecret = string.Empty;
string oauthtoken = Request.QueryString["oauth_token"];
string oauthsignaturemethod = "HMAC-SHA1";
string oauthversion = "1.0";
string oauthnonce = HttpUtility.UrlEncode(Guid.NewGuid().ToString("N"));
TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
string oauthtimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
string url = "https://api.twitter.com/oauth/access_token?oauth_verifier=" + Uri.EscapeDataString(oauthverifier);
SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
basestringParameters.Add("oauth_version", oauthversion);
basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
basestringParameters.Add("oauth_nonce", oauthnonce);
basestringParameters.Add("oauth_signature_method", oauthsignaturemethod);
basestringParameters.Add("oauth_timestamp", oauthtimestamp);
basestringParameters.Add("oauth_token", EncodeCharacters(oauthtoken));
//Build the signature string
StringBuilder baseString = new StringBuilder();
baseString.Append("POST" + "&");
baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split('?')[0]) + "&"));
foreach (KeyValuePair<string, string> entry in basestringParameters)
{
baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
}
//Remove the trailing ambersand char last 3 chars - %26
string finalBaseString = baseString.ToString().Substring(0, baseString.Length - 3);
//Build the signing key
string signingKey = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) + "&" +
EncodeCharacters(Uri.EscapeDataString(oauthtokensecret));
//Sign the request
HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
string oauthsignature = Convert.ToBase64String(
hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));
//Tell Twitter we don't do the 100 continue thing
ServicePointManager.Expect100Continue = false;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@url);
StringBuilder authorizationHeaderParams = new StringBuilder();
authorizationHeaderParams.Append("OAuth ");
authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauthconsumerkey) + "\",");
authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauthnonce) + "\",");
authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(oauthsignature) + "\",");
authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauthsignaturemethod) + "\",");
authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauthtimestamp) + "\",");
authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(oauthtoken) + "\"");
authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
webRequest.Headers.Add("Authorization", authorizationHeaderParams.ToString());
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
//Allow us a reasonable timeout in case Twitter's busy
webRequest.Timeout = 3 * 60 * 1000;
string responseFromServer;
try
{
//webRequest.Proxy = new WebProxy("enter proxy details/address");
HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
Stream dataStream = webResponse.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
responseFromServer = reader.ReadToEnd();
// responseFromServer; ;
}
catch (WebException e)
{
HttpWebResponse errorR = e.Response as HttpWebResponse;
Stream dataStream = errorR.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string dat = responseFromServer = reader.ReadToEnd();
}
您在下一行中忘记了一个逗号 (,)。
您的线路:
authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
应该是:
authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\",");