首页 > 解决方案 > 如何生成 OAuth1.0 签名

问题描述

我必须使用OAuth1.0. 在响应头中,它需要访问令牌、OAuth Nonce、时间戳和 OAuthSignature。我编写了创建方法 Timestamp以及 OAuthNonce 如何使用这些参数生成 OAuthsignature?它使用 HMAC-SHA1 方法对签名进行哈希处理。如何创建生成 OAuth 签名密钥的方法。任何人都可以建议使用这些参数创建签名的方法吗?提前致谢。

private static string CreateOAuthTimestamp()
        {
            var nowUtc = DateTime.UtcNow;
            var timeSpan = nowUtc - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            var timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
            return timestamp;
        }

 private string CreateOauthNonce()
        {
            return Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
        }

标签: oauthauthorizationasp.net-authorizationoauth-1.0a

解决方案


我找到了一个创建 Oauth 1.0 签名的方法。它需要 api 请求的所有参数在 SHA1 算法中进行散列。

private string CreateOauthSignature
       (string resourceUrl, string oauthNonce, string oauthTimestamp , 
SortedDictionary<string, string> requestParameters)
    {
        //Add the standard oauth parameters to the sorted list        
        requestParameters.Add("oauth_consumer_key", consumerKey);
        requestParameters.Add("oauth_nonce", oauthNonce);
        requestParameters.Add("oauth_signature_method", OauthSignatureMethod);
        requestParameters.Add("oauth_timestamp", oauthTimestamp);
        requestParameters.Add("oauth_token", accessToken);
        requestParameters.Add("oauth_version", OauthVersion);

        var sigBaseString = requestParameters.ToWebString();

        var signatureBaseString = string.Concat
        ("GET", "&", Uri.EscapeDataString(resourceUrl), "&",
                            Uri.EscapeDataString(sigBaseString.ToString()));

        //Using this base string, encrypt the data using a composite of the 
        //secret keys and the HMAC-SHA1 algorithm.
        var compositeKey = string.Concat(Uri.EscapeDataString(consumerKeySecret), "&",
                                         Uri.EscapeDataString(accessTokenSecret));

        string oauthSignature;
        using (var hasher = new HMACSHA1(Encoding.ASCII.GetBytes(compositeKey)))
        {
            oauthSignature = Convert.ToBase64String(
                hasher.ComputeHash(Encoding.ASCII.GetBytes(signatureBaseString)));
        }
        return oauthSignature;
    }  

ToWebstring() 是一种扩展方法,用于将排序字典转换为 Web 字符串并对特殊字符进行编码。创建签名后,可以将其与其他标头参数一起包含在 Http 请求的授权标头中。随机数、时间戳、访问令牌等。


推荐阅读