Skip to content

Instantly share code, notes, and snippets.

@tkssharma
Created October 17, 2022 19:42
Show Gist options
  • Save tkssharma/d4153a8c1a2d5e69bcb544dcd6d3e701 to your computer and use it in GitHub Desktop.
Save tkssharma/d4153a8c1a2d5e69bcb544dcd6d3e701 to your computer and use it in GitHub Desktop.
const { CognitoUserPool, CognitoUser, AuthenticationDetails } = require("amazon-cognito-identity-js");
const debug = require("debug");
const error = debug("authorizer:error:lambda");
const verbose = debug("authorizer:verbose:lambda");
// DEBUG : authorizer:*
const cognitoUserPool = () => (
new CognitoUserPool({
UserPoolId: config.cognito.USER_POOL_ID,
ClientId: config.cognito.CLIENT_ID
})
);
function authenticateUser(auth) {
const tmp = auth.split(' ');
const buf = new Buffer(tmp[1], 'base64');
// create a buffer and tell it the data coming in is base64
const plain_auth = buf.toString();
// read it back out as a string
console.log("Decoded Authorization ", plain_auth);
const credentials = plain_auth.split(':');
// split on a ':'
const poolData = {
UserPoolId: process.env.USER_POOL_ID,
// Your user pool id here
ClientId: process.env.CLIENT_ID
// Your client id here
};
verbose(poolData);
const username = credentials[0];
const password = credentials[1];
verbose(authenticationDetails);
const userPool = cognitoUserPool();
const user = new CognitoUser({ Username: username, Pool: userPool });
const authenticationData = { Username: username, Password: password };
const authenticationDetails = new AuthenticationDetails(authenticationData);
return new Promise((resolve, reject) =>
user.authenticateUser(authenticationDetails, {
onSuccess: result => resolve(result),
onFailure: err => reject(err)
})
);
}
exports.handler = async function (event, context, callback) {
try {
verbose(event.authorizationToken);
await authenticateUser(event.authorizationToken);
callback(null, generatePolicy('user', 'Allow', event.methodArn));
} catch (err) {
error(err);
callback(null, generatePolicy('user', 'Deny', event.methodArn));
}
};
// Help function to generate an IAM policy
const generatePolicy = function (principalId, effect, resource) {
const authResponse = {};
authResponse.principalId = principalId;
if (effect && resource) {
const policyDocument = {};
policyDocument.Version = '2012-10-17';
policyDocument.Statement = [{
"Action": 'execute-api:Invoke',
"Effect": effect,
"Resource": resource
}];
authResponse.policyDocument = policyDocument;
}
return authResponse;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment