Created
September 11, 2021 08:53
-
-
Save techministrator/2aebab11f700ef1807bb635a1a9ad9d5 to your computer and use it in GitHub Desktop.
Authenticate CloudFront Viewer Request with Lambda@Edge Basic Auth with User/Pass stored in SSM Parameter Store
This file contains 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
'use strict' | |
var AWS = require('aws-sdk') | |
var ssm = new AWS.SSM({region: 'us-east-1'}) | |
const getParameter = async (params) => { | |
try { | |
const resp = await ssm.getParameter(params).promise() | |
console.log(resp.Parameter.Value) | |
return resp.Parameter.Value | |
} catch (err) { | |
console.error(err) | |
return err | |
} | |
} | |
exports.handler = async (event, context) => { | |
try { | |
const request = event.Records[0].cf.request | |
console.log("EVENT: \n" + JSON.stringify(event, null, 2)) | |
const headers = request.headers | |
const authUser = await getParameter({Name: '/dev/frontend-service/username'}) | |
const authPass = await getParameter({Name: '/dev/frontend-service/password', WithDecryption: true}) | |
const authString = 'Basic ' + Buffer.from(authUser + ':' + authPass).toString('base64') | |
if (typeof headers.authorization == 'undefined' || headers.authorization[0].value != authString) { | |
const body = 'Unauthorized' | |
const response = { | |
status: '401', | |
statusDescription: 'Unauthorized', | |
body: body, | |
headers: { | |
'www-authenticate': [{key: 'WWW-Authenticate', value:'Basic'}] | |
}, | |
} | |
console.log('Authentication failed from ' + request.clientIp) | |
return response | |
} else { | |
console.log('Authentication success from ' + request.clientIp) | |
return request | |
} | |
} catch (err) { | |
console.error(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment