Skip to content

Instantly share code, notes, and snippets.

@bethesque
Created February 25, 2020 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bethesque/cf8d8b0504946c4e4b1ccba5e3c4b5f8 to your computer and use it in GitHub Desktop.
Save bethesque/cf8d8b0504946c4e4b1ccba5e3c4b5f8 to your computer and use it in GitHub Desktop.
API Gateway custom auth
const accountId = process.env.ACCOUNT_ID;
const region = process.env.REGION;
const basicAuthUsername = process.env.BASIC_AUTH_USERNAME;
const basicAuthPassword = process.env.BASIC_AUTH_PASSWORD;
const validateAuth = authorizationHeader => {
if (!authorizationHeader) return false;
const encodedCreds = authorizationHeader.split(" ")[1];
const plainCreds = new Buffer(encodedCreds, "base64").toString().split(":");
const username = plainCreds[0];
const password = plainCreds[1];
return (
username === basicAuthUsername &&
password === basicAuthPassword
);
};
exports.handler = async function(event) {
console.log("authorising request", { event });
const token = event.headers["Authorization"];
const id = event.requestContext["apiId"];
const principalId = `arn:aws:execute-api:${region}:${accountId}:${id}/*/*/*/*`;
let effect = validateAuth(token) ? "Allow" : "Deny";
const policyDocument = {
Version: "2012-10-17",
Statement: [
{
Action: "execute-api:Invoke",
Effect: effect,
Resource: principalId
}
]
};
return { principalId, context: null, policyDocument };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment