Search code examples
c#coinbase-api

C# Coinbase Pro API How to Trouble Shoot Responses. 401


I keep Getting 401 responses from coinbase pro and I have double checked my passphrase and api key and they are correct. Is there any other reason I would get Unauth response


            var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString("F0", CultureInfo.InvariantCulture);
            var method = "GET";
            var requestPath = "/accounts";
            var body = "";
            var data = timestamp + method + requestPath + body;
            var secret = "***";

            var signedMessage = GetHMACInHex(secret, data);

            var client = new HttpClient()
            {
                BaseAddress = new Uri("https://api.pro.coinbase.com")
            };

            client.DefaultRequestHeaders.Add("CB-ACCESS-SIGN", signedMessage);
            client.DefaultRequestHeaders.Add("CB-ACCESS-KEY", "***");
            client.DefaultRequestHeaders.Add("CB-ACCESS-TIMESTAMP", timestamp);
            client.DefaultRequestHeaders.Add("CB-ACCESS-PASSPHRASE", "***");
            client.DefaultRequestHeaders.Add("User-Agent", "CoinbaseProClient");

This is how I Sign the Data

static string GetHMACInHex(string key, string data)
        {
            var decoded = Convert.FromBase64String(key);
            var dataBytes = Encoding.UTF8.GetBytes(data);


            using (var hmac = new HMACSHA256(decoded))
            {
                
                var hash = hmac.ComputeHash(dataBytes);
                return Convert.ToBase64String(hash);
            }
        }

Solution

  • 401 status code is returned by Coinbase when following validation of the resource fails on POST or PUT requests:

    • authentication_error- Invalid auth (generic)
    • invalid_token- Invalid Oauth token
    • revoked_token- Revoked Oauth token
    • expired_token- Expired Oauth token

    If your problem is not listed here, you may miss to pass DefaultRequestHeaders.

    client.DefaultRequestHeaders
          .Accept
          .Add(new MediaTypeWithQualityHeaderValue("application/json"));