问题
I have been pulling my hair to figure our what goes wrong here and apparently I haven't been able to. I try to create a basic structure to work with Twitter API over OAuth in .NET (C#) but something is wrong and I cannot see what that is.
For example, when I send a request in order to obtain a request token, I get back 401 Unauthorized response back with a message as follows:
Failed to validate oauth signature and token
The signature base that I use to create the signature is as follows (I replaced my actual Consumer Key with a dummy value):
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
The signing key only consists of my Consumer Key Secret and an ampersand given the fact that I don't have a token secret available yet (again, I replaced my actual Consumer Key with a dummy value):
signingKey: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&
At the end, I end up with the following Authorization header (again, dummy Consumer Key):
OAuth oauth_callback="http%3A%2F%2Flocalhost%3A44444%2Faccount%2Fauth",oauth_consumer_key="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",oauth_nonce="NjM0NzkyMzk0OTk2ODEyNTAz",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1343631900",oauth_version="1.0",oauth_signature="ttLvZ2Xzq4CHt%2BNM4pW7X4h1wRA%3D"
The code I use for this is as follows (it is a little bit long but I'd rather paste it here instead of giving a gist URL or something):
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; }
}
}
There is a mix of new .NET HttpClient
here but the Authorization header generation code is clear to understand.
So, what would be my problem here and what am I missing?
Edit:
I gave it a try for different endpoint (such as /1/account/update_profile.json), and it works when I send a request whose body doesn't require encoding. E.g: location=Marmaris
works but location=Marmaris, Turkey
doesn't work even if I encode it using Uri.EscapeDataString
.
Edit:
I gave it a try with Twitter OAuth tool to see if there is any particular difference between my signature base and twitter's and I can see that twitter's encoding is different than mine. For example, Twitter produces location%3DMarmaris%252C%2520Turkey
value for location=Marmaris, Turkey
but what I produce is location%3DMarmaris%2C%20Turkey
.
回答1:
It seems that all the problem was related to encoding issue and for now, it seems that I solved the problem out. Here is a few information about the issue:
When we are creating the signature base, the parameter values needs to be encoded twice. For example, I have a collection as below:
var collection = new List<KeyValuePair<string, string>>();
collection.Add(new KeyValuePair<string, string>("location", Uri.EscapeDataString(locationVal)));
collection.Add(new KeyValuePair<string, string>("url", Uri.EscapeDataString(profileUrl)));
When I pass this to GenerateSignature method, that method encodes these one more time and this results percentage signs to be encoded as %25
and this made it work. One of my problems was solved but I still couldn't issue a request token request successfully at that time.
Then, I looked at the "request_token" request and saw the below line of code:
OAuthCredential creds = new OAuthCredential(_consumerKey) {
CallbackUrl = "http://localhost:44444/account/auth"
};
I was sending the CallbackUrl
as it is in order for it to be encoded but as twitter needs to encode things twice for the signature base, I thought that might be the problem. Then, I replaced this code with the following one:
OAuthCredential creds = new OAuthCredential(_consumerKey) {
CallbackUrl = Uri.EscapeDataString("http://localhost:44444/account/auth")
};
One more change I made was inside the GenerateAuthHeader
method since I don't need to encode CallbackUrl
twice.
//don't encode it here again.
//we already did that and auth header doesn't require it to be encoded twice
if (!string.IsNullOrEmpty(_oAuthState.Credential.CallbackUrl))
sortedDictionary.Add(OAuthCallback, oAuthState.Credential.CallbackUrl);
And I made it run w/o any problems.
回答2:
Tugberk here is another OAuth lib, no magic here.
http://oauth.googlecode.com/svn/code/csharp/OAuthBase.cs
来源:https://stackoverflow.com/questions/11717144/twitter-oauth-authorization-issue-with-net-c