this is Node.16
const { CognitoJwtVerifier } = require('aws-jwt-verify');
const AWS = require('aws-sdk');
const verifier = CognitoJwtVerifier.create({
userPoolId: process.env.userPoolId,
tokenUse: 'id',
clientId: process.env.clientAppId,
});
exports.handler = async (event, context) => {
const authorizationHeader = event.headers.Authorization;
if (!authorizationHeader) {
return {
statusCode: 401,
body: JSON.stringify({ message: 'Unauthorized - No Token' }),
headers: {
"Access-Control-Allow-Headers" : "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS,POST"
}
};
}
const token = authorizationHeader.split(' ')[1]; // Extract the token from the Authorization header
try {
const verifiedToken = await verifier.verify(token);
console.log('Authorization Header:', authorizationHeader);
const cognitoidentity = new AWS.CognitoIdentity({apiVersion: '2014-06-30', region: process.env.region});
const logins = {
[`cognito-idp.${process.env.region}.amazonaws.com/${process.env.userPoolId}`]: token
};
const getIdParams = {
IdentityPoolId: process.env.identityPoolId, // replace with your Identity Pool ID
Logins: logins
};
const idResponse = await cognitoidentity.getId(getIdParams).promise();
const getCredentialsParams = {
IdentityId: idResponse.IdentityId,
Logins: logins
};
const credentialsResponse = await cognitoidentity.getCredentialsForIdentity(getCredentialsParams).promise();
return {
statusCode: 200,
body: JSON.stringify({
message: 'Token validated successfully',
identityId: idResponse.IdentityId,
credentials: credentialsResponse.Credentials // Return AWS temporary credentials
}),
headers: {
"Access-Control-Allow-Headers" : "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS,POST"
}
};
} catch (error) {
console.log('Token validation error:', error);
return {
statusCode: 401,
body: JSON.stringify({ message: 'Unauthorized - Invalid Token' }),
headers: {
"Access-Control-Allow-Headers" : "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS,POST"
}
};
}
};