简体   繁体   中英

AWS Cloudfront SetCookie in PHP

I am trying to set a cookie to view private content from AWS Cloudfront

http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-setting-signed-cookie-custom-policy.html

They give an example cookie header:

Set-Cookie: Domain=d111111abcdef8.cloudfront.net; Path=/; Secure; HttpOnly; CloudFront-Key-Pair-Id=APKA9ONS7QCOWEXAMPLE

I created the following php code

setcookie (
  'CloudFront-Key-Pair Id',
  'MYID',
  0,
  '/',
  'mycloudfrontsub.cloudfront.net',
  true, 
  true
);

But the cookie is not set. The cookie is only set if I take out the domain name.

I think this is due to calling the setcookie in a script after session_start. I tried adding this, but it's required before session_start()

session_set_cookie_params(0, '/', 'duvoxso6rm38g.cloudfront.net);

Do I need to do something like this?

//close local session, then open new one for aws
$id=SID;
session_write_close();
session_set_cookie_params(0, '/', 'mysub.cloudfront.net');
session_start();
setcookie(...);
session_write_close();
session_set_cookie_params(0, '/', 'originaldomain.com');    
session_start();

The cookies do not show up in the browser because you send a cookie for a domain A from domain B. That is silently ignored by the browsers for security reasons. This is a browser feature not a PHP thing.

If you want to use signed cookies with CloudFront you need to use a CNAME for the CloudFront distribution that is a subdomain of you PHP server domain. A more detailed answer can be found under: https://mnm.at/markus/2015/04/05/serving-private-content-through-cloudfront-using-signed-cookies/

In short: assume you want to use the domain example.com . You serve the PHP files under www.example.com . Then you can use the CNAME media.example.com for the d111111abcdef8.cloudfront.net. To send the cookies from the PHP side to the CloudFront Server you need to use the domain example.com in the Cookie.

The referenced site does also notice that you should use the PHP function header() to send the cookie, not setcookie() . This is because the setcookie function does some encoding that ruins the singing parameter created with the functions mentioned on the site.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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