AWS の Cognito から JWT Access Token を取得する方法です。
ライブラリーのインストール
sudo npm install amazon-cognito-identity-js
get_token.js
// ---------------------------------------------------------------
//
// get_token.js
//
// Feb/19/2022
// ---------------------------------------------------------------
'use strict'
console.error("*** start ***")
var cognito = require('amazon-cognito-identity-js')
const dotenv = require('dotenv')
dotenv.config()
const user_pool_id = `${process.env.USER_POOL_ID}`
const user_pool_client_id = `${process.env.USER_POOL_CLIENT_ID}`
const usr = `${process.env.USR}`
const password = `${process.env.PASSWORD}`
console.error(usr)
console.error(password)
var poolData = {
UserPoolId : user_pool_id,
ClientId : user_pool_client_id
}
var userPool = new cognito.CognitoUserPool(poolData)
var authenticationData = {
Username : usr,
Password : password
}
var authenticationDetails = new cognito.AuthenticationDetails(authenticationData)
var userData = {
Username : usr,
Pool : userPool
}
var cognitoUser = new cognito.CognitoUser(userData)
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
console.log('access token')
console.log(result.getAccessToken().getJwtToken())
},
onFailure: function(err) {
console.error("*** error ***")
console.error('error ' + err)
},
})
console.error("*** end ***")
.env
USER_POOL_ID="ap-northeast-1_510w*****"
USER_POOL_CLIENT_ID="818aso07e5pd8dj*******"
USR="aaa@example.com"
PASSWORD="secret123"
実行スクリプト
export NODE_PATH=/usr/local/lib/node_modules
node get_token.js
次の環境で確認しました。
$ uname -a
Linux iwata 5.13.0-27-generic #29-Ubuntu SMP Wed Jan 12 17:36:47 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
$ node --version
v17.5.0
$ npm --version
8.5.1