Skip to content

Instantly share code, notes, and snippets.

@kloudsamurai
Created May 9, 2019 22:37
Show Gist options
  • Save kloudsamurai/64e205f553121675c0ad1a29a7cb86bd to your computer and use it in GitHub Desktop.
Save kloudsamurai/64e205f553121675c0ad1a29a7cb86bd to your computer and use it in GitHub Desktop.
Amazon AWS Cloudfront Lambda @ Edge to Manage Session ID Creation and Updates
'use strict';
const crypto = require("crypto");
const sessionKey = 'CLOUDFRONT_SESSION_ID';
const regex = '(^|[^;]+)\\s*' + sessionKey + '\\s*=\\s*([^;]+)';
const expirationMinutes = 2 * 60; // 2 hours
const SHTS = 'Strict-Transport-Security';
function getSessionCookie(cookieValue) {
const sessionId = cookieValue.match(regex);
return sessionId ? sessionId.pop() : null;
}
// Add set-cookie header (including path)
const setSessionCookie = (sessionId, response) => {
if (sessionId === null) {
sessionId = crypto.randomBytes(16).toString("hex");
}
const date = new Date();
// 2 hour expiration
date.setTime(date.getTime() + (expirationMinutes * 60 * 1000));
const expires = `expires=${date.toGMTString()}`;
const cookieValue = `${sessionKey}=${sessionId}; Path=/; ${expires}; Secure;`;
console.log(`Setting cookie ${cookieValue}`);
response.headers['set-cookie'] = [{key: "Set-Cookie", value: cookieValue}];
};
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
const response = event.Records[0].cf.response;
const requestHeaders = request.headers;
const responseHeaders = response.headers;
let hasSessionCookie = false;
let sessionId = null;
if (!responseHeaders || !responseHeaders['content-type']) {
callback(null, response);
return;
}
// only process html and json content type
const contentType = responseHeaders['content-type'][0].value;
if (!contentType.includes('html') && !contentType.includes('json')) {
callback(null, response);
return;
}
// strict transport security
responseHeaders[SHTS.toLowerCase()] = [{
key: SHTS,
value: 'max-age=31536000'
}];
if (requestHeaders && requestHeaders.cookie) {
for (let i = 0; i < requestHeaders.cookie.length; i++) {
const cookieValue = requestHeaders.cookie[i].value;
if (cookieValue.indexOf(sessionKey) >= 0) {
hasSessionCookie = true;
sessionId = getSessionCookie(cookieValue);
console.log(`${sessionKey}: ${sessionId}`);
break;
}
}
}
setSessionCookie(sessionId, response);
callback(null, response);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment