2016-11-18 83 views
2

我一直在嘗試使用.NET AWS Cloudfront API爲我的S3存儲桶創建簽名cookie,但每當我發送帶有創建的cookie的HTTP請求時,我都會得到「禁止」的結果。在這段代碼中有什麼我做錯了嗎?謝謝。在C#中使用AWS Cloudfront API創建簽名Cookie

CookiesForCannedPolicy cookies = AmazonCloudFrontCookieSigner.GetCookiesForCannedPolicy(
    @"http://distribution123abc.cloudfront.net/*", 
    "KEYPAIRID", 
    new FileInfo(@"C:\bla\privatekey.pem"), 
    DateTime.Now.AddHours(1)); 

Uri target = new Uri(@"http://distribution123abc.cloudfront.net"); 
HttpWebRequest pleaseWork = (HttpWebRequest)WebRequest.Create(@"http://distribution123abc.cloudfront.net/files/test.txt"); 

if (pleaseWork.CookieContainer == null) 
{ 
    pleaseWork.CookieContainer = new CookieContainer(); 
} 
pleaseWork.CookieContainer.Add(new Cookie(cookies.Signature.Key, cookies.Signature.Value) { Domain = target.Host }); 
pleaseWork.CookieContainer.Add(new Cookie(cookies.KeyPairId.Key, cookies.KeyPairId.Value) { Domain = target.Host }); 
pleaseWork.CookieContainer.Add(new Cookie(cookies.Expires.Key, cookies.Expires.Value) { Domain = target.Host }); 

try 
{ 
    WebResponse response = pleaseWork.GetResponse(); 
    Console.WriteLine("Response content length: " + response.ContentLength); 
} 
catch(WebException e) 
{ 
    Console.WriteLine(e.Message); 
} 

回答

1

我找到了解決方案。我不得不改變兩件事:

首先,我不得不使用簽名的cookie作爲自定義策略,而不是使用罐裝策略(因此使用「策略」cookie而不是「過期」cookie)。

其次,我爲我的Cookie設置的域名不正確。我需要將域設置爲「.cloudfront.net」,而不是爲我的發佈指定域。

這是什麼樣子,到底我的代碼:

CookiesForCustomPolicy cookies = AmazonCloudFrontCookieSigner.GetCookiesForCustomPolicy(
    @"http://distribution123abc.cloudfront.net/*", 
    new StreamReader(@"C:\bla\privatekey.pem"), 
    "KEYPAIRID", 
    DateTime.Now.AddHours(1), 
    DateTime.Now.AddHours(-1), 
    "1.1.1.1"); 

string domain = ".cloudfront.net"; 
HttpWebRequest pleaseWork = (HttpWebRequest)WebRequest.Create(@"http://distribution123abc.cloudfront.net/files/test.txt"); 

if (pleaseWork.CookieContainer == null) 
{ 
    pleaseWork.CookieContainer = new CookieContainer(); 
} 
pleaseWork.CookieContainer.Add(new Cookie(cookies.Signature.Key, cookies.Signature.Value) { Domain = domain }); 
pleaseWork.CookieContainer.Add(new Cookie(cookies.KeyPairId.Key, cookies.KeyPairId.Value) { Domain = domain }); 
pleaseWork.CookieContainer.Add(new Cookie(cookies.Policy.Key, cookies.Policy.Value) { Domain = domain }); 

try 
{ 
    WebResponse response = pleaseWork.GetResponse(); 
    Console.WriteLine("Response content length: " + response.ContentLength); 
} 
catch(WebException e) 
{ 
    Console.WriteLine(e.Message); 
} 
+1

有一次,我改變了IP範圍0.0.0.0/0這個完美工作,謝謝 – ScottieMc