Last active
February 2, 2018 22:00
Node.js CLI script to login a Cognito user and print JWT tokens
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
/** | |
* Logs the user into the specified Cognito User Pool and prints out JWT tokens | |
* @example | |
* $ node cognito-login.js username="john.doe" password="j0hn.d0e" user-pool-id="us-east-1_Xxxxxxxx" app-client-id="2axxyyxxyxxxyyxxxyy" | |
* { | |
* "accessToken": "eyJra...aQ", | |
* "identityToken": "eyJra...iA", | |
* "refreshToken": "eyJj...Wg" | |
* } | |
*/ | |
const Cognito = require("amazon-cognito-identity-js"); | |
const args = process.argv.slice(2).reduce((acc, arg) => { | |
let [k, v = true] = arg.split("="); | |
acc[k] = v; | |
return acc; | |
}, {}); | |
const requiredArgs = ["username", "password", "user-pool-id", "app-client-id"]; | |
if (!requiredArgs.every(a => a in args)) { | |
console.error( | |
`usage: node cognito-login.js username="john.doe" password="j0hn.d0e" user-pool-id="us-east-1_Xxxxxxxx" app-client-id="2axxyyxxyxxxyyxxxyy"` | |
); | |
console.error("Error: missing arguments"); | |
return; | |
} | |
const authenticationDetails = new Cognito.AuthenticationDetails({ | |
Username: args.username, | |
Password: args.password | |
}); | |
const userPool = new Cognito.CognitoUserPool({ | |
UserPoolId: args["user-pool-id"], | |
ClientId: args["app-client-id"] | |
}); | |
const cognitoUser = new Cognito.CognitoUser({ | |
Username: args.username, | |
Pool: userPool | |
}); | |
cognitoUser.authenticateUser(authenticationDetails, { | |
onSuccess: function(result) { | |
const object = { | |
accessToken: result.getAccessToken().getJwtToken(), | |
identityToken: result.getIdToken().getJwtToken(), | |
refreshToken: result.getRefreshToken().getToken() | |
}; | |
console.log(JSON.stringify(object, null, 4)); | |
}, | |
onFailure: function(err) { | |
console.error(err); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment