0

我正在使用 Apple 新闻 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"
        }
    ]
}

生成签名有什么不正确的吗?

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

请指导我找出解决方案。

4

1 回答 1

1

我没有时间浏览您的全部代码,并建议您Channel Data在尝试POSTjson 之前从一个更简单的请求开始,但我注意到了一些潜在的位:

  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'"内容类型 = "multipart/form-data; boundary=[boundary]"其中边界是用于划分内容的任何字符串。

另请参阅我关于使用 Python 的提示,最重要的是确保您使用的是包含文件夹的article.json路径(而不是文件的路径)。最后,这是我自己将Python 翻译成 Swift 的过程。

于 2018-08-17T10:59:56.593 回答