【问题标题】:Twitter OAuth Authorization Issue with .NET (C#).NET (C#) 的 Twitter OAuth 授权问题
【发布时间】:2012-07-31 10:19:16
【问题描述】:

我一直在努力弄清楚我们这里出了什么问题,显然我无法弄清楚。我尝试创建一个基本结构,以便在 .NET (C#) 中通过 OAuth 使用 Twitter API,但出现了问题,我看不到那是什么。

例如,当我发送request in order to obtain a request token 时,我会返回 401 Unauthorized response 并返回如下消息:

验证 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&

最后,我得到了以下授权标头(同样,虚拟消费者密钥):

OAuth oauth_callback="http%3A%2F%2Flocalhost%3A44444%2Faccount%2Fauth",oauth_consumer_key="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",oauth_nonce="NjM0NzkyMzk0OTk2ODEyNTAz",oauth_signature_method="HMAC-SHA1",oauth_09",oauth_09",oauth_363 "1.0",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 有效,但即使我使用 Uri.EscapeDataString 对其进行编码,location=Marmaris, Turkey 也无效。

编辑:

我用 Twitter OAuth 工具试了一下,看看我的签名库和 twitter 之间是否有任何特别的区别,我可以看到 twitter 的编码与我的不同。例如,Twitter 为 location=Marmaris, Turkey 生成 location%3DMarmaris%252C%2520Turkey 值,但我生成的是 location%3DMarmaris%2C%20Turkey

【问题讨论】:

  • 只是出于好奇......你为什么不使用DotNetAuth呢?
  • @James 这是一个庞大的库,使用它时感觉很神奇,我不习惯。我对垃圾收集级别的魔法很满意,但对 DotNetOpenAuth 种类不满意。
  • @tugberk - 至少比较一下 DotNetAuth 如何做你想做的事。看来您甚至不想尝试了解它的作用。
  • @Ramhound 是问题的重点还是以任何方式回答了问题?
  • @tugberk 回来编辑你的帖子,然后跟进答案,干得不错。 OAuth 很棘手,这有望帮助其他想要编写自己的代码的人。

标签: c# oauth twitter twitter-oauth


【解决方案1】:

似乎所有问题都与编码问题有关,现在看来我已经解决了问题。以下是有关该问题的一些信息:

当我们创建签名库时,参数值需要被编码两次。例如,我有一个如下的集合:

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)));

当我将它传递给 GenerateSignature 方法时,该方法会再编码一次,这会导致百分号被编码为%25,这使它工作。我的一个问题解决了,但当时我仍然无法成功发出请求令牌请求。

然后,我查看了“request_token”请求,看到了下面这行代码:

OAuthCredential creds = new OAuthCredential(_consumerKey) {
    CallbackUrl = "http://localhost:44444/account/auth"
};

我发送CallbackUrl 是为了对其进行编码,但由于 twitter 需要对签名库进行两次编码,我认为这可能是问题所在。然后,我将这段代码替换为以下代码:

OAuthCredential creds = new OAuthCredential(_consumerKey) { 
    CallbackUrl = Uri.EscapeDataString("http://localhost:44444/account/auth")
};

我在GenerateAuthHeader 方法内部进行了另一项更改,因为我不需要对CallbackUrl 进行两次编码。

//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);

我让它运行没有任何问题。

【讨论】:

    【解决方案2】:

    这里的 Tugberk 是另一个 OAuth 库,这里没有魔法。

    http://oauth.googlecode.com/svn/code/csharp/OAuthBase.cs

    【讨论】:

    • 我的实现基于此,但我也遇到了一些问题(很可能是编码问题)。这就是我需要自定义 impl 的原因。
    猜你喜欢
    • 2015-09-16
    • 2017-10-05
    • 1970-01-01
    • 2012-04-08
    • 2015-01-22
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    相关资源
    最近更新 更多