Last active
November 22, 2023 11:46
-
-
Save danishi/968cd415536bd2f7d4c84cd04e05bc96 to your computer and use it in GitHub Desktop.
Basic authentication with CloudFront KeyValueStore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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