我正试图从Twitter OAuth获取请求令牌,但我一直收到“401未经授权”的响应,但我不知道原因。我已尽力按照签名创建的过程进行操作,并且曾经遇到过“400错误请求”问题,最终成功解决它并得到了有效请求,但现在面对的却是401错误。
我感觉自己可能错过了非常简单的东西,但我就是找不出来。
这是我正在使用的代码:
我正在使用 .Net 4.5,所以
编辑:
我注意到
我感觉自己可能错过了非常简单的东西,但我就是找不出来。
这是我正在使用的代码:
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("https://api.twitter.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
string oauth_callback = Uri.EscapeUriString("oob");
string oauth_signature_method = "HMAC-SHA1";
string oauth_timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
string oauth_consumer_key = OAUTH_KEY;
string oauth_version = "1.0";
// Generate signature
string baseString = "POST&";
baseString += Uri.EscapeDataString(client.BaseAddress + "oauth/request_token") + "&";
// Each oauth value sorted alphabetically
baseString += Uri.EscapeDataString("oauth_callback=" + oauth_callback + "&");
baseString += Uri.EscapeDataString("oauth_consumer_key=" + oauth_consumer_key + "&");
baseString += Uri.EscapeDataString("oauth_nonce=" + oauth_nonce + "&");
baseString += Uri.EscapeDataString("oauth_signature_method=" + oauth_signature_method + "&");
baseString += Uri.EscapeDataString("oauth_timestamp=" + oauth_timestamp + "&");
baseString += Uri.EscapeDataString("oauth_version=" + oauth_version + "&");
string signingKey = Uri.EscapeDataString(OAUTH_SECRET) + "&";
HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
string oauth_signature = Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(baseString)));
client.DefaultRequestHeaders.Add("Authorization", "OAuth " +
"oauth_nonce=\"" + oauth_nonce + "\"," +
"oauth_callback=\"" + oauth_callback + "\"," +
"oauth_signature_method=\"" + oauth_signature_method + "\"," +
"oauth_timestamp=\"" + oauth_timestamp + "\"," +
"oauth_consumer_key=\"" + oauth_consumer_key + "\"," +
"oauth_signature=\"" + Uri.EscapeDataString(oauth_signature) + "\"," +
"oauth_version=\"" + oauth_version + "\""
);
HttpResponseMessage response = await client.PostAsJsonAsync("oauth/request_token", "");
var responseString = await response.Content.ReadAsStringAsync();
}
我正在使用 .Net 4.5,所以
Uri.EscapeDataString()
应该能给出正确的百分号编码字符串。编辑:
我注意到
oauth_nonce
值有时包含非字母数字字符,因此我将变量计算更改为以下内容:string nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
string oauth_nonce = new string(nonce.Where(c => Char.IsLetter(c) || Char.IsDigit(c)).ToArray());
很遗憾,这并没有帮助。
我还尝试过对Authorization
头中的所有值使用Uri.EscapeUriData()
,以及在每个逗号后面添加一个空格(因为Twitter的文档是这样说的),但这也没有起作用。
DateTime.UtcNow
:string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.UtcNow.Ticks.ToString()));
- Martin Costellooauth/request_token
。 - Patrick Hofman