Poloniex C# Trading API webRequest 回来了 (403) Forbidden

Posted

技术标签:

【中文标题】Poloniex C# Trading API webRequest 回来了 (403) Forbidden【英文标题】:Poloniex C# Trading API webRequest comes back (403) Forbidden 【发布时间】:2018-09-24 18:28:07 【问题描述】:

我的代码已经达到了测试访问的基本要求,但我从服务器收到了旧的错误 (403),我已经确认我使用了正确的 API 密钥/秘密对。我的代码(通过 Unity 3D 实现的 C#)如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System.Net;

public class PolonScript : MonoBehaviour
    
    public TextMesh OutputText;    

    const string _apiKey = "---apiKey---";
    const string _apiSecret = "---apiSecret---";

    void Start()
       
        string nonce = DateTime.Now.ToString ("HHmmss");      

        const string WEBSERVICE_URL = "https://poloniex.com/tradingApi";
        try 
        
            var webRequest = System.Net.WebRequest.Create (WEBSERVICE_URL);
            if (webRequest != null) 
            
                webRequest.Method = "POST";
                //webRequest.Timeout = 12000;
                webRequest.ContentType = "application/x-www-form-urlencoded";    

                byte[] dataStream = 
                    Encoding.UTF8.GetBytes("command=returnBalances&nonce=" + nonce);    

                webRequest.Headers.Add("Key", _apiKey);
                webRequest.Headers.Add("Sign", genHMAC (dataStream));   

                Stream newStream = webRequest.GetRequestStream();
                newStream.Write(dataStream, 0, dataStream.Length);
                newStream.Close();    

                using (System.IO.Stream s = 
                        webRequest.GetResponse().GetResponseStream()) 
                
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(s)) 
                    
                        var jsonResponse = sr.ReadToEnd();
                        OutputText.text = jsonResponse.ToString();
                    
                
            
         
        catch (WebException ex) 
        
            OutputText.text = ex.ToString();
                   
    
    //end-of-start()

    private string genHMAC(byte[] dataStreamInput)
        
        byte [] APISecret_Bytes = 
               System.Text.Encoding.UTF8.GetBytes(_apiSecret);
        HMACSHA512 hmac = new HMACSHA512(APISecret_Bytes);    

        var signBytes = hmac.ComputeHash(dataStreamInput);    

        string HexDecString = string.Empty;
        for (int i = 0; i < signBytes.Length; i++)
        
            HexDecString += signBytes[i].ToString("X2");
        

        return HexDecString;    
    

那么为什么我会收到 (403) Forbidden 使用准确的凭据?

我试过这个看看原因:

catch (WebException ex) 
           
    OutputText.text = ex.Response.Headers.ToString ();

并收到以下内容

//Date: Sat, 14 Apr 2018 15:34:56 GMT
//Content-Type: application/json
//Transfer-Encoding: chunked
//Connection: keep-alive
//Set-Cookie: __cfduid=dd1b32592915674669120afbf8181141b1523720096; expires=Sun, 14-Apr-19 15:34:56 GMT; path=/; domain=.poloniex.com; HttpOnly
//Cache-Control: private
//Expect-CT: max-age=604800, report-uri="https://report-//uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
//Server: cloudflare
//CF-RAY: 40b73d4b8c98552e-ORD

【问题讨论】:

【参考方案1】:

我预计这是因为您的 Sign 标头无效。


您可以使用假的nonce 和假的secret 仔细检查您的签名功能是否正常,并验证sign 是否正确

发布数据:nonce=123456&amp;command=returnBalances

随机数:123456

秘密:123456

sign 将是:b56174398987d15deee73885ca178ba82c414c7f27e763a9aa3cfc41c5b1373980ed83638bbf8c66dc62c20cbf35e770ad264af8571d22bc7c96fae9740dac0

如果标志不同,请分享您的genHMAC 代码功能。


你可以试试这个版本来生成sign header:

private readonly string _apiKey = "123456"; 
private readonly string _apiSecret = "123456"; 
private long nonce = DateTime.Now.Ticks;




private string CreateSignature()

    //string msg = string.Format("012", _apiKey);

    return ByteArrayToString(SignHMACSHA512(_apiSecret, StringToByteArray(_apiKey))).ToUpper();


private static byte[] SignHMACSHA512(String key, byte[] data)

    HMACSHA512 hashMaker = new HMACSHA512(Encoding.ASCII.GetBytes(key));
    return hashMaker.ComputeHash(data);


private static byte[] StringToByteArray(string str)

    return System.Text.Encoding.ASCII.GetBytes(str);


private static string ByteArrayToString(byte[] hash)  //rimuove - e converte in bite

    return BitConverter.ToString(hash).Replace("-", "").ToLower();

然后:

   const string WEBSERVICE_URL = "https://poloniex.com/tradingApi";
    try
    


        var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
        if (webRequest != null)
        
            webRequest.Method = "POST";
            webRequest.Timeout = 12000;
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Headers.Add("Key", _apiKey);
            webRequest.Headers.Add("Sign", CreateSignature());     // keysecret 

            var postData = "&nonce=&command=returnBalances";
            var data = Encoding.ASCII.GetBytes(postData);




            using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
            
                using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                
                    var jsonResponse = sr.ReadToEnd();
                    Console.WriteLine(String.Format("Response: 0", jsonResponse));
                
            
        
    
    catch (Exception ex)
    
        Console.WriteLine(ex.ToString());
    

来源:https://bitcointalk.org/index.php?topic=1590683.0

【讨论】:

我得到 F21E6ECC2EE587A4DF217EEDFA38F87CC72.... 等等。我的 genHMAC 是: private string genHMAC(byte[] dataStreamInput) byte [] APISecret_Bytes = System.Text.Encoding.UTF8.GetBytes(_apiSecret); HMACSHA512 hmac = 新 HMACSHA512(APISecret_Bytes); var signBytes = hmac.ComputeHash(dataStreamInput);字符串 HexDecString = string.Empty; for (int i = 0; i 我更新答案以添加 C# CreateSignature() 函数和发布请求示例

以上是关于Poloniex C# Trading API webRequest 回来了 (403) Forbidden的主要内容,如果未能解决你的问题,请参考以下文章

请求Poloniex API

Poloniex API 文档

连接到 Poloniex Push-API

Poloniex 新的 Websocket API

Poloniex 通过 Autobahn 推送 WAMP API,断开与对等 tcp 的连接

poloniex 403禁止使用python3.5