Skip to content

Instantly share code, notes, and snippets.

@y-o-u
Created February 9, 2021 08:12
Show Gist options
  • Save y-o-u/a59172e1641462b2f6082de129120948 to your computer and use it in GitHub Desktop.
Save y-o-u/a59172e1641462b2f6082de129120948 to your computer and use it in GitHub Desktop.
function login(email, password, callback) {
const request = require('request');
const jwt = require('jsonwebtoken');
//const region = configuration.region;
const clientId = configuration.clientId;
const userPoolId = configuration.userPoolId;
let userData = {
"AuthParameters": {
"USERNAME": email,
"PASSWORD": password
},
"AuthFlow": "USER_PASSWORD_AUTH",
"ClientId": clientId
}
let options = {
'method': 'POST',
'url': 'https://cognito-idp.ap-northeast-1.amazonaws.com/',
'headers': {
'X-Amz-Target': 'AWSCognitoIdentityProviderService.InitiateAuth',
'Content-Type': 'application/x-amz-json-1.1'
},
body: JSON.stringify(userData)
};
request(options, function (error, response) {
if (error) throw new Error(error);
let resJson = JSON.parse(response.body);
const token = resJson.AuthenticationResult.IdToken;
const pem = configuration.PEM.replace(/\\n/g, '\n');
jwt.verify(token, pem, { algorithms: ['RS256'] }, function(err, decodedToken) {
if(err !== null){
console.error(err);
}else{
// other verify
if(decodedToken.aud !== clientId) {
console.error(err);
return callback(err);
}
if(decodedToken.iss !== `https://cognito-idp.ap-northeast-1.amazonaws.com/${userPoolId}`) {
console.error(err);
return callback(err);
}
const nowTime = Math.floor(new Date().getTime() / 1000);
if(nowTime > decodedToken.exp) {
console.error(err);
return callback(err);
}
//console.log(decodedToken);
console.log("Success");
callback(null, {
//username: email, // Requires UsernameがONの時はいる
user_id: decodedToken.sub,
email: decodedToken.email
});
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment