在C#中生成OAuth1签名

时间:2016-02-28 01:38:38

标签: c# windows oauth signature

我有一个大问题。我在C#中使用UWP Windows 10应用程序,我想使用OAuth 1。

一切都差不多但签名错了。但是,我在Microsoft GitHub上找到了示例代码。显然,我做了一些修改......

我的代码:

private async Task GoCo()
{
        String LifeInvaderUrl = "http://stage.api.lolilolz.be/v8/login";

        string timeStamp = GetTimeStamp();
        string nonce = GetNonce();
        string consumerKey = "noob-stage";
        string consumerSecret = "TOPSECRETxxXXxx";

        string SigBaseStringParams = "oauth_consumer_key=" + consumerKey;
        SigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
        SigBaseStringParams += "&" + "oauth_timestamp=" + timeStamp;
        SigBaseStringParams += "&" + "oauth_nonce=" + nonce;
        SigBaseStringParams += "&" + "oauth_version=1.0";

        string SigBaseString = "POST&";
        SigBaseString += Uri.EscapeDataString(LifeInvaderUrl) + "&" + Uri.EscapeDataString(SigBaseStringParams);

        String Signature = GetSignature(SigBaseString, consumerSecret);

        string authorizationHeaderParams = "oauth_consumer_key=\"" + consumerKey + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"" + timeStamp + "\", oauth_nonce=\"" + nonce +   "\", oauth_vesrion=\"1.0\", oauth_signature=\"" + Uri.EscapeDataString(Signature)+ "\"";

        HttpClient httpClient = new HttpClient();

        //...

}

签名生成器方法:

string GetSignature(string sigBaseString, string consumerSecretKey)
{
        IBuffer KeyMaterial = CryptographicBuffer.ConvertStringToBinary(consumerSecretKey + "&", BinaryStringEncoding.Utf8);
        MacAlgorithmProvider HmacSha1Provider = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
        CryptographicKey MacKey = HmacSha1Provider.CreateKey(KeyMaterial);
        IBuffer DataToBeSigned = CryptographicBuffer.ConvertStringToBinary(sigBaseString, BinaryStringEncoding.Utf8);
        IBuffer SignatureBuffer = CryptographicEngine.Sign(MacKey, DataToBeSigned);
        string Signature = CryptographicBuffer.EncodeToBase64String(SignatureBuffer);

        return Signature;
}

提前谢谢你:)

4 个答案:

答案 0 :(得分:2)

oauth_vesrion类型应该是oauth_version

答案 1 :(得分:2)

您的基本字符串参数不正确。对于OAuth 1.0,需要对其进行排序。我已经创建了用于创建基本字符串的通用函数。您可以使用它。

`        private static string GetSignatureBaseString(string strUrl, string TimeStamp,
            string Nonce, string strConsumer, string strOauthToken, SortedDictionary<string, string> data)
        {
            //1.Convert the HTTP Method to uppercase and set the output string equal to this value.
            string Signature_Base_String = "POST";
            Signature_Base_String = Signature_Base_String.ToUpper();

            //2.Append the ‘&’ character to the output string.
            Signature_Base_String = Signature_Base_String + "&";

            //3.Percent encode the URL and append it to the output string.
            string PercentEncodedURL = Uri.EscapeDataString(strUrl);
            Signature_Base_String = Signature_Base_String + PercentEncodedURL;

            //4.Append the ‘&’ character to the output string.
            Signature_Base_String = Signature_Base_String + "&";

            //5.append OAuth parameter string to the output string.
            var parameters = new SortedDictionary<string, string>
            {
                {"oauth_consumer_key", strConsumer},
                { "oauth_token", strOauthToken },
                {"oauth_signature_method", "HMAC-SHA1"},
                {"oauth_timestamp", TimeStamp},
                {"oauth_nonce", Nonce},
                {"oauth_version", "1.0"}
            };

            //6.append parameter string to the output string.
            foreach (KeyValuePair<string, string> elt in data)
            {
                parameters.Add(elt.Key, elt.Value);
            }

            bool first = true;
            foreach (KeyValuePair<string, string> elt in parameters)
            {
                if (first)
                {
                    Signature_Base_String = Signature_Base_String + Uri.EscapeDataString(elt.Key + "=" + elt.Value);
                    first = false;
                }
                else
                {
                    Signature_Base_String = Signature_Base_String + Uri.EscapeDataString("&" + elt.Key + "=" + elt.Value);
                }
            }

            return Signature_Base_String;
        }

` 使用上面的功能,您将获得基础,您可以使用您的秘密密钥将其传递给下面的功能并获得签名

private static string GetSha1Hash(string key, string base)
    {
        var encoding = new System.Text.ASCIIEncoding();

        byte[] keyBytes = encoding.GetBytes(key);
        byte[] messageBytes = encoding.GetBytes(base);

        string strSignature = string.Empty;

        using (HMACSHA1 SHA1 = new HMACSHA1(keyBytes))
        {
            var Hashed = SHA1.ComputeHash(messageBytes);
            strSignature = Convert.ToBase64String(Hashed);
        }

        return strSignature;
    }

答案 2 :(得分:0)

您的签名基本参数不正确。这些值按其编码名称排序,如果相等,则根据其编码值排序。因此,您的SigBaseStringParams应该看起来像这样:

    string SigBaseStringParams = "oauth_consumer_key=" + consumerKey;
    SigBaseStringParams += "&" + "oauth_nonce=" + nonce;
    SigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
    SigBaseStringParams += "&" + "oauth_timestamp=" + timeStamp;
    SigBaseStringParams += "&" + "oauth_version=1.0";

答案 3 :(得分:0)

 public static Dictionary<string, string> ParseQueryString(string queryString)
{
    var nvc = HttpUtility.ParseQueryString(queryString);
    return nvc.AllKeys.ToDictionary(k => k, k => nvc[k]);
}
public static string CreateQueryString(Dictionary<string, string> parameters)
{
    return string.Join("&", parameters.Select(kvp =>
       string.Format("{0}={1}", kvp.Key, HttpUtility.UrlEncode(kvp.Value))));
}
private string CreateOauthSignature(string resourceUrl, CustomMethod method, string oauthNonce, string oauthTimestamp)
{
    //firstly we need to add the standard oauth parameters to the sorted list
    SortedDictionary<string, string> requestParameters = new SortedDictionary<string, string>();
    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);

    string url = string.Empty;
    if (resourceUrl.Contains("?"))
    {
        var queryParam = resourceUrl.Substring((resourceUrl.IndexOf("?") + 1));
        var list = ParseQueryString(queryParam);
        var queryString = CreateQueryString(list);
        url = resourceUrl.Replace(resourceUrl.Substring(resourceUrl.IndexOf("?")), "");
        foreach (var item in list)
            requestParameters.Add(item.Key, item.Value);
    }
    var sigBaseString = requestParameters.ToWebString();
    var signatureBaseString = string.Concat
    (method.ToString(), "&", Uri.EscapeDataString(url), "&",
                        Uri.EscapeDataString(sigBaseString.ToString()));
     // method refers to request type e.g. GET,POST
    //Using this base string, we then 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;
}