繁体   English   中英

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

[英]Publish article for Apple news API using C# - (401) Unauthorized

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

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

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

请指导我找出解决方案。

我没有时间浏览整个代码,建议您在尝试POST JSON之前先从一个更简单的Channel Data请求开始,但是我注意到了一些潜在的问题:

  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'"content-type = "multipart/form-data; boundary=[boundary]" ,其中boundary是用于分割内容的任何字符串。

另请参阅有关使用Python的技巧 ,最重要的是确保您使用的是包含article.json的文件夹的路径(而不是文件的路径)。 最后,这是我自己将 Python转换为Swift的过程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM