0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Node.js: Cognito から Access Token を取得

Last updated at Posted at 2022-02-19

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?