我一直在努力弄清楚我们这里出了什么问题,显然我做不到。我尝试创建一个基本结构,以便在 .NET(C#)中通过 OAuth 使用 Twitter API,但是出现了问题,我看不到那是什么。
例如,当我发送请求以获取请求令牌时,我会返回 401 Unauthorized 响应并返回如下消息:
无法验证 oauth 签名和令牌
我用来创建签名的签名库如下(我用虚拟值替换了我的实际消费者密钥):
POST&HTTP%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%3A%2F%2Flocalhost%3A44444%2Faccount%2Fauth%26oauth_consumer_key%3XXXXXXXXXXXXXXXXXXXXXXXXXXX%26oauth_nonce%3DNjM0NzkyMzk0OTk2ODEyNTAz%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1343631900%26oauth_version% 3D1.0
考虑到我还没有可用的令牌秘密,签名密钥仅包含我的消费者密钥密钥和一个 & 符号(再次,我用一个虚拟值替换了我的实际消费者密钥):
签名密钥:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&
最后,我得到了以下 Authorization 标头(再次,虚拟消费者密钥):
OAuth oauth_callback="http%3A%2F%2Flocalhost%3A44444%2Faccount%2Fauth",oauth_consumer_key="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",oauth_nonce="NjM0NzkyMzk0OTk2ODEyNTAz",oauth_signature_method="HMAC-SHA1",oauth_timestamp="13436310000"" ,oauth_signature="ttLvZ2Xzq4CHt%2BNM4pW7X4h1wRA%3D"
我为此使用的代码如下(它有点长,但我宁愿将它粘贴在这里,而不是提供 gist URL 或其他东西):
public class OAuthMessageHandler : DelegatingHandler {
private const string OAuthConsumerKey = "oauth_consumer_key";
private const string OAuthNonce = "oauth_nonce";
private const string OAuthSignature = "oauth_signature";
private const string OAuthSignatureMethod = "oauth_signature_method";
private const string OAuthTimestamp = "oauth_timestamp";
private const string OAuthToken = "oauth_token";
private const string OAuthVersion = "oauth_version";
private const string OAuthCallback = "oauth_callback";
private const string HMACSHA1SignatureType = "HMAC-SHA1";
private readonly OAuthState _oAuthState;
public OAuthMessageHandler(OAuthCredential oAuthCredential, OAuthSignatureEntity signatureEntity,
IEnumerable<KeyValuePair<string, string>> parameters, HttpMessageHandler innerHandler) : base(innerHandler) {
_oAuthState = new OAuthState() {
Credential = oAuthCredential,
SignatureEntity = signatureEntity,
Parameters = parameters,
Nonce = GenerateNonce(),
SignatureMethod = GetOAuthSignatureMethod(),
Timestamp = GetTimestamp(),
Version = GetVersion()
};
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
//add the auth header
request.Headers.Authorization = new AuthenticationHeaderValue(
"OAuth", GenerateAuthHeader(_oAuthState, request)
);
return base.SendAsync(request, cancellationToken);
}
private string GetTimestamp() {
TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
return Convert.ToInt64(timeSpan.TotalSeconds).ToString();
}
private string GetVersion() {
return "1.0";
}
private string GetOAuthSignatureMethod() {
return HMACSHA1SignatureType;
}
private string GenerateNonce() {
return Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
}
private string GenerateSignature(OAuthState oAuthState, HttpRequestMessage request) {
//https://dev.twitter.com/docs/auth/creating-signature
//http://garyshortblog.wordpress.com/2011/02/11/a-twitter-oauth-example-in-c/
SortedDictionary<string, string> signatureCollection = new SortedDictionary<string, string>();
//Required for all requests
signatureCollection.Add(OAuthConsumerKey, oAuthState.Credential.ConsumerKey);
signatureCollection.Add(OAuthNonce, oAuthState.Nonce);
signatureCollection.Add(OAuthVersion, oAuthState.Version);
signatureCollection.Add(OAuthTimestamp, oAuthState.Timestamp);
signatureCollection.Add(OAuthSignatureMethod, oAuthState.SignatureMethod);
//Parameters
if (oAuthState.Parameters != null) {
oAuthState.Parameters.ForEach(x => signatureCollection.Add(x.Key, x.Value));
}
//Optionals
if (!string.IsNullOrEmpty(oAuthState.Credential.Token))
signatureCollection.Add(OAuthToken, oAuthState.Credential.Token);
if (!string.IsNullOrEmpty(oAuthState.Credential.CallbackUrl))
signatureCollection.Add(OAuthCallback, oAuthState.Credential.CallbackUrl);
//Build the signature
StringBuilder strBuilder = new StringBuilder();
strBuilder.AppendFormat("{0}&", request.Method.Method.ToUpper());
strBuilder.AppendFormat("{0}&", Uri.EscapeDataString(request.RequestUri.ToString()));
signatureCollection.ForEach(x =>
strBuilder.Append(
Uri.EscapeDataString(string.Format("{0}={1}&", x.Key, x.Value))
)
);
//Remove the trailing ambersand char from the signatureBase.
//Remember, it's been urlEncoded so you have to remove the
//last 3 chars - %26
string baseSignatureString = strBuilder.ToString();
baseSignatureString = baseSignatureString.Substring(0, baseSignatureString.Length - 3);
//Build the signing key
string signingKey = string.Format(
"{0}&{1}", Uri.EscapeDataString(oAuthState.SignatureEntity.ConsumerSecret),
string.IsNullOrEmpty(oAuthState.SignatureEntity.OAuthTokenSecret) ? "" : Uri.EscapeDataString(oAuthState.SignatureEntity.OAuthTokenSecret)
);
//Sign the request
using (HMACSHA1 hashAlgorithm = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey))) {
return Convert.ToBase64String(
hashAlgorithm.ComputeHash(
new ASCIIEncoding().GetBytes(baseSignatureString)
)
);
}
}
private string GenerateAuthHeader(OAuthState oAuthState, HttpRequestMessage request) {
SortedDictionary<string, string> sortedDictionary = new SortedDictionary<string, string>();
sortedDictionary.Add(OAuthNonce, Uri.EscapeDataString(oAuthState.Nonce));
sortedDictionary.Add(OAuthSignatureMethod, Uri.EscapeDataString(oAuthState.SignatureMethod));
sortedDictionary.Add(OAuthTimestamp, Uri.EscapeDataString(oAuthState.Timestamp));
sortedDictionary.Add(OAuthConsumerKey, Uri.EscapeDataString(oAuthState.Credential.ConsumerKey));
sortedDictionary.Add(OAuthVersion, Uri.EscapeDataString(oAuthState.Version));
if (!string.IsNullOrEmpty(_oAuthState.Credential.Token))
sortedDictionary.Add(OAuthToken, Uri.EscapeDataString(oAuthState.Credential.Token));
if (!string.IsNullOrEmpty(_oAuthState.Credential.CallbackUrl))
sortedDictionary.Add(OAuthCallback, Uri.EscapeDataString(oAuthState.Credential.CallbackUrl));
StringBuilder strBuilder = new StringBuilder();
var valueFormat = "{0}=\"{1}\",";
sortedDictionary.ForEach(x => {
strBuilder.AppendFormat(valueFormat, x.Key, x.Value);
});
//oAuth parameters has to be sorted before sending, but signature has to be at the end of the authorization request
//http://stackoverflow.com/questions/5591240/acquire-twitter-request-token-failed
strBuilder.AppendFormat(valueFormat, OAuthSignature, Uri.EscapeDataString(GenerateSignature(oAuthState, request)));
return strBuilder.ToString().TrimEnd(',');
}
private class OAuthState {
public OAuthCredential Credential { get; set; }
public OAuthSignatureEntity SignatureEntity { get; set; }
public IEnumerable<KeyValuePair<string, string>> Parameters { get; set; }
public string Nonce { get; set; }
public string Timestamp { get; set; }
public string Version { get; set; }
public string SignatureMethod { get; set; }
}
}
这里混合了新的 .NET HttpClient
,但 Authorization 标头生成代码很容易理解。
那么,我的问题是什么,我错过了什么?
编辑:
我尝试了不同的端点(例如/1/account/update_profile.json),当我发送一个正文不需要编码的请求时它可以工作。例如:location=Marmaris
有效,但location=Marmaris, Turkey
即使我使用Uri.EscapeDataString
.
编辑:
我用 Twitter OAuth 工具试了一下,看看我的签名库和 twitter 之间是否有任何特别的区别,我可以看到 twitter 的编码与我的不同。例如,Twitter 产生location%3DMarmaris%252C%2520Turkey
价值,location=Marmaris, Turkey
但我产生的是location%3DMarmaris%2C%20Turkey
.