使用C#发布Apple News API的文章-(401)未经授权

时间:2018-07-24 13:11:16

标签: c# asp.net apple-news

我正在使用Apple news API发布文章。

我创建了新帐户,也创建了新频道。

下面是我正在使用的代码段。

        string channel_id = "{Channel_Id}";
        string api_key_id = "{Key_Id}";
        string api_key_secret = "{Secret}";
        var path = "https://news-api.apple.com/channels/" + channel_id + "/articles";

        var httpWebRequest = (HttpWebRequest)WebRequest.Create(path);
        httpWebRequest.ContentType = "multipart/form-data";
        httpWebRequest.Method = "POST";
        httpWebRequest.Accept = "application/json";
        httpWebRequest.Host = "news-api.apple.com";
        httpWebRequest.UseDefaultCredentials = true;
        httpWebRequest.PreAuthenticate = true;

        httpWebRequest.ProtocolVersion = HttpVersion.Version11;
        httpWebRequest.KeepAlive = true;
        string appleDate = String.Format("{0}Z", DateTime.UtcNow.ToString("s"));
        string credentials = String.Format("{0}:{1}", "Content-Disposition", "form-data; ");
        credentials += String.Format("{0}:{1}", "filename", "article.json; ");
        credentials += String.Format("{0}:{1}", "name", "article.json; ");

        credentials += String.Format("{0}","HHMAC; ");
        credentials += String.Format("{0}={1}", "key", api_key_id + "; ");

        string decodedSecret = base64Decode(api_key_secret);
        string canonical_request = path + "POST" + appleDate ;
        string hash = Class1.HmacSha256Digest(canonical_request, decodedSecret);
        string Encodedhash = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(hash));

        credentials += String.Format("{0}={1}", "signature", Encodedhash + "; ");
        credentials += String.Format("{0}={1}", "date", appleDate + "; ");


        httpWebRequest.Headers.Add("Authorization", credentials);

        using (StreamReader r = new StreamReader(Directory.GetCurrentDirectory() + ("/article.json")))
        {
            string json = r.ReadToEnd();
            dynamic jsonObj = JsonConvert.DeserializeObject(json);

            ASCIIEncoding encoding = new ASCIIEncoding();
            Byte[] bytes = encoding.GetBytes(json);
            Stream newStream = httpWebRequest.GetRequestStream();
            newStream.Write(bytes, 0, bytes.Length);
            newStream.Close();
        }
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
        }

这是base64Decode函数

public static string base64Decode(string data)
        {
            var base64EncodedBytes = System.Convert.FromBase64String(data);
            return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
        }

这里是转换Sha256Digest的类

public static class Class1
    {
        public static string HmacSha256Digest(this string message, string secret)
        {
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] keyBytes = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(message);
            System.Security.Cryptography.HMACSHA256 cryptographer = new System.Security.Cryptography.HMACSHA256(keyBytes);

            byte[] bytes = cryptographer.ComputeHash(messageBytes);

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

每当我尝试发布API时,都会出现以下错误消息:

““远程服务器返回错误:(401)未经授权”。

当我尝试使用Postman发布API请求时,出现以下错误消息:

{
    "errors": [
        {
            "code": "WRONG_SIGNATURE"
        }
    ]
}

是否有任何不正确的特征来生成签名?

我研究了几篇文章,但找不到任何解决方案。

请指导我找出解决方案。

1 个答案:

答案 0 :(得分:1)

我没有时间遍历整个代码,建议您在尝试Channel Data json之前先从一个更简单的POST请求开始,但是我注意到了一些可能的地方:< / p>

  1. 您在应该始终使用UTF8的地方使用ASCII编码。
  2. 您从Base64去除了连字符,但Apple只去除了返回符, 空格
  3. 应将规范的请求写为:"POST[url][date][contentType]",其中 url = "https://news-api.apple.com/channels/[channelID]/articles"日期的格式为"yyyy-MM-dd'T'HH:mm:ss'Z'",并且< strong> content-type = "multipart/form-data; boundary=[boundary]",其中 boundary 是用于分割内容的任何字符串。

另请参见my tips on using Python,最重要的是确保您使用的是包含article.json的文件夹的路径(而不是文件的路径)。最后是my own translation的Python到Swift中。