I'm trying to create a Cloudfront function that will generate signed cookies allowing access to certain specified files as specified by my application. To do this, I'm copying the methodology from https://gist.github.com/darbelaez/d5b802a8f0600076a3f19fc0161a367e, which uses JS in an HTML file to accomplish the same purpose.
When I test this function, it claims everything works and it shows the cookies in the output. However, when I access the page running this script, the Set-Cookie header does not appear in the response. The "Foo=Bar" header does, so I can tell the script is running in the first place.
Is this how you set a cookie in a Cloudfront script? Does anyone know what would prevent the cookie from actually being set in the response? The event type is set to "Viewer Response".
function handler(event) {
var params = event.request.querystring;
var response = event.response;
var cookies = response.cookies;
// Set expiration date to 24 hours from now
var d = new Date();
d.setTime(d.getTime() + (24*60*60*1000));
var expires = "expires="+ d.toUTCString();
// Copy the signed URL parameters into signed cookies
["Policy", "Signature", "Key-Pair-Id"].forEach(function(name){
console.log(name + " => " + JSON.stringify(params[name]));
if(params[name] && params[name].value) {
cookies["Cloudfront-" + name] = {
value: params[name].value,
attributes: expires + ";path=/;SameSite=None;Secure"
};
}
});
console.log(JSON.stringify(response));
console.log(JSON.stringify(params));
console.log(JSON.stringify(cookies));
// Prove that this script is actually running
response.headers.foo = {value: "bar"};
return response;
}
EDIT: I discovered an error in my code - I was looking for URL parameters with the prefix "Cloudfront-" like the cookies have. I updated that above. Now I am getting the Set-Cookie headers in my response... but further calls to the same Cloudfront distribution do not include those cookies in the request. I realize that's a slightly different question from the one I originally asked, but I would still like an answer if anyone knows how to use signed cookies in cross-origin requests like this.
EDIT 2: To clarify, my app is hosted on a domain like my.app.com, while the videos are hosted on [uniqueid].cloudfront.net.