REST API authentication (OAuth 1.0) using C#

13,993

Solution 1

After studying https://oauth.net/core/1.0/#signing_process again, I finally got it right. Note, the Escape function is not essential I just happened to stumble upon that one while trying to make things work.

        const string consumerKey = "";
        const string consumerSecret = "";
        const string tokenSecret = "";
        const string tokenValue = "";
        const string url = "https://api.bricklink.com/api/store/v1/items/part/3001";

        string Escape(string s)
        {
            // https://stackoverflow.com/questions/846487/how-to-get-uri-escapedatastring-to-comply-with-rfc-3986
            var charsToEscape = new[] {"!", "*", "'", "(", ")"};
            var escaped = new StringBuilder(Uri.EscapeDataString(s));
            foreach (var t in charsToEscape)
            {
                escaped.Replace(t, Uri.HexEscape(t[0]));
            }
            return escaped.ToString();
        }

        var httpWebRequest = (HttpWebRequest) WebRequest.Create(url);
        httpWebRequest.Method = "GET";

        var timeStamp = ((int) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString();
        var nonce = Convert.ToBase64String(Encoding.UTF8.GetBytes(timeStamp));

        var signatureBaseString = Escape(httpWebRequest.Method.ToUpper()) + "&";
        signatureBaseString += EscapeUriDataStringRfc3986(url.ToLower()) + "&";
        signatureBaseString += EscapeUriDataStringRfc3986(
            "oauth_consumer_key=" + EscapeUriDataStringRfc3986(consumerKey) + "&" +
            "oauth_nonce=" + EscapeUriDataStringRfc3986(nonce) + "&" +
            "oauth_signature_method=" + EscapeUriDataStringRfc3986("HMAC-SHA1") + "&" +
            "oauth_timestamp=" + EscapeUriDataStringRfc3986(timeStamp) + "&" +
            "oauth_token=" + EscapeUriDataStringRfc3986(tokenValue) + "&" +
            "oauth_version=" + EscapeUriDataStringRfc3986("1.0"));
        Console.WriteLine(@"signatureBaseString: " + signatureBaseString);

        var key = EscapeUriDataStringRfc3986(consumerSecret) + "&" + EscapeUriDataStringRfc3986(tokenSecret);
        Console.WriteLine(@"key: " + key);
        var signatureEncoding = new ASCIIEncoding();
        var keyBytes = signatureEncoding.GetBytes(key);
        var signatureBaseBytes = signatureEncoding.GetBytes(signatureBaseString);
        string signatureString;
        using (var hmacsha1 = new HMACSHA1(keyBytes))
        {
            var hashBytes = hmacsha1.ComputeHash(signatureBaseBytes);
            signatureString = Convert.ToBase64String(hashBytes);
        }
        signatureString = EscapeUriDataStringRfc3986(signatureString);
        Console.WriteLine(@"signatureString: " + signatureString);

        string SimpleQuote(string s) => '"' + s + '"';
        var header =
            "OAuth realm=" + SimpleQuote("") + "," +
            "oauth_consumer_key=" + SimpleQuote(consumerKey) + "," +
            "oauth_nonce=" + SimpleQuote(nonce) + "," +
            "oauth_signature_method=" + SimpleQuote("HMAC-SHA1") + "," +
            "oauth_timestamp=" + SimpleQuote(timeStamp) + "," +
            "oauth_token=" + SimpleQuote(tokenValue) + "," +
            "oauth_version=" + SimpleQuote("1.0") + "," +
            "oauth_signature= " + SimpleQuote(signatureString);
        Console.WriteLine(@"header: " + header);
        httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, header);

        var response = httpWebRequest.GetResponse();
        var characterSet = ((HttpWebResponse) response).CharacterSet;
        var responseEncoding = characterSet == ""
            ? Encoding.UTF8
            : Encoding.GetEncoding(characterSet ?? "utf-8");
        var responsestream = response.GetResponseStream();
        if (responsestream == null)
        {
            throw new ArgumentNullException(nameof(characterSet));
        }
        using (responsestream)
        {
            var reader = new StreamReader(responsestream, responseEncoding);
            var result = reader.ReadToEnd();
            Console.WriteLine(@"result: " + result);
        }

Solution 2

For anyone who is looking for way simpler solution. This works with WooCommerce and probably with other services. For WooCommerce token/tokenSecret is null.

var client = new RestClient($"{StoreHttp}/wp-json/wc/v3/products")
{
    Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, token, tokenSecret)
};

var request = new RestRequest(Method.GET);
RestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Share:
13,993
halvorsen
Author by

halvorsen

Updated on June 04, 2022

Comments

  • halvorsen
    halvorsen almost 2 years

    I'm trying to connect to the Bricklink REST API using OAuth (http://apidev.bricklink.com/redmine/projects/bricklink-api/wiki/Authorization).

    It should be pretty straight forward. However, I'm currently stuck and keep getting a SIGNATURE_INVALID error. My current attempt is shown below. Any suggestions?

            const string consumerKey = "";
            const string consumerSecret = "";
            const string tokenSecret = "";
            const string tokenValue = "";
            const string url = "https://api.bricklink.com/api/store/v1/items/part/3001";
    
            var httpWebRequest = (HttpWebRequest) WebRequest.Create(url);
            httpWebRequest.Method = "GET";
    
            var timeStamp = ((int) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString();
            var nonce = Convert.ToBase64String(Encoding.UTF8.GetBytes(timeStamp));
    
            var signatureBaseString = httpWebRequest.Method.ToUpper() + "&";
            signatureBaseString = signatureBaseString + url.ToLower() + "&";
            signatureBaseString = signatureBaseString + "oauth_consumer_key=" + consumerKey + "&";
            signatureBaseString = signatureBaseString + "oauth_nonce=" + nonce + "&";
            signatureBaseString = signatureBaseString + "oauth_signature_method=" + "HMAC-SHA1" + "&";
            signatureBaseString = signatureBaseString + "oauth_timestamp=" + timeStamp + "&";
            signatureBaseString = signatureBaseString + "oauth_token=" + tokenValue + "&";
            signatureBaseString = signatureBaseString + "oauth_version=" + "1.0";
            signatureBaseString = Uri.EscapeDataString(signatureBaseString);
            Console.WriteLine(signatureBaseString);
    
            var signatureEncoding = new ASCIIEncoding();
            var keyBytes = signatureEncoding.GetBytes(consumerSecret + "&" + tokenSecret);
            var signatureBaseBytes = signatureEncoding.GetBytes(signatureBaseString);
            string signatureString;
            using (var hmacsha1 = new HMACSHA1(keyBytes))
            {
                var hashBytes = hmacsha1.ComputeHash(signatureBaseBytes);
                signatureString = Convert.ToBase64String(hashBytes);
            }
            signatureString = Uri.EscapeDataString(signatureString);
            Console.WriteLine(signatureString);
    
            string SimpleQuote(string x) => '"' + x + '"';
            var header =
                "OAuth realm=" + SimpleQuote("") + "," +
                "oauth_consumer_key=" + SimpleQuote(consumerKey) + "," +
                "oauth_nonce=" + SimpleQuote(nonce) + "," +
                "oauth_signature_method=" + SimpleQuote("HMAC-SHA1") + "," +
                "oauth_timestamp=" + SimpleQuote(timeStamp) + "," +
                "oauth_token=" + SimpleQuote(tokenValue) + "," +
                "oauth_version=" + SimpleQuote("1.0") + "," +
                "oauth_signature= " + SimpleQuote(signatureString);
            Console.WriteLine(header);
            httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, header);
    
            var response = httpWebRequest.GetResponse();
            var characterSet = ((HttpWebResponse) response).CharacterSet;
            var responseEncoding = characterSet == ""
                ? Encoding.UTF8
                : Encoding.GetEncoding(characterSet ?? "utf-8");
            var responsestream = response.GetResponseStream();
            if (responsestream == null)
            {
                throw new ArgumentNullException(nameof(characterSet));
            }
            using (responsestream)
            {
                var reader = new StreamReader(responsestream, responseEncoding);
                var result = reader.ReadToEnd();
                Console.WriteLine(result);
            }
    

    I know that consumerKey, consumerSecret, tokenSecret, and tokenValue are correct as I can connect using the bricklink-api (https://www.npmjs.com/package/bricklink-api) using JavaScript.

  • wannadream
    wannadream almost 5 years
    Have you tested your method with 2 legged OAuth?
  • halvorsen
    halvorsen almost 5 years
    No, BL just uses an OAuth 1.0 like flow.
  • MCattle
    MCattle almost 3 years
    Just for the benefit of other readers, the RestClient above is from the RestSharp library.
  • atakan
    atakan over 2 years
    RestSharp does the job, thx for the hint @ramunas !
  • Eric Eskildsen
    Eric Eskildsen about 2 years
    For anyone else doing one-legged OAuth 1, pass null for token and tokenSecret on line 3. You can change the signature method through parameter 5 if needed. Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, null, null, OAuthSignatureMethod.HmacSha256).