簡體   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