Skip to content

Instantly share code, notes, and snippets.

@danishi
Last active November 22, 2023 11:46
Show Gist options
  • Select an option

  • Save danishi/968cd415536bd2f7d4c84cd04e05bc96 to your computer and use it in GitHub Desktop.

Select an option

Save danishi/968cd415536bd2f7d4c84cd04e05bc96 to your computer and use it in GitHub Desktop.
Basic authentication with CloudFront KeyValueStore
import cf from 'cloudfront';
const kvsId = '<KEY_VALUE_STORE_ID>';
// This fails if the key value store is not associated with the function
const kvsHandle = cf.kvs(kvsId)
async function handler(event) {
const request = event.request;
const headers = request.headers;
const method = request.method;
let username = '';
let password = '';
try {
username = await kvsHandle.get('username');
password = await kvsHandle.get('password');
} catch (err) {
console.log(`Kvs key lookup failed: ${err}`);
throw err;
}
const authorization = `Basic ${(`${username}:${password}`).toString('base64')}`;
const origin = '*';
// Preflight requests skip basic authentication
if (method === "OPTIONS") {
return {
statusCode: 204,
statusDescription: "NoContent",
headers: {
"access-control-allow-origin": { value: origin }
}
};
}
// Handling of authentication fail
if (headers.authorization === undefined ||
headers.authorization.value !== authorization) {
return {
statusCode: 401,
statusDescription: 'Unauthorized',
headers: {
'www-authenticate': {value: 'Basic'}
}
};
}
return event.request;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment