我一直在尝试使用.NET AWS Cloudfront API为我的S3存储桶创建已签名的Cookie,但每当我发送带有创建的Cookie的HTTP请求时,我都会得到“禁止”的结果。我在这段代码中做错了吗?感谢。
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);
}
答案 0 :(得分:1)
我找到了解决方案。我不得不改变两件事:
首先,我必须使用签名的cookie来实现自定义策略,而不是使用预设策略(因此使用"策略" cookie而不是" Expires" 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);
}