2
3

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.

AWS: AppSync を認証モード COGNITO_USER_POOLS で使う

Last updated at Posted at 2022-02-26

こちらのサンプルの認証モードを
API KEY から、COGNITO_USER_POOLS にした時の使い方です。
AWS: AppSync の使い方

IdToken (JWT) の取得

get_jwt.sh
USER_POOL_ID="ap-northeast-1_*****"
CLIENT_ID="*****"
#
USER_EMAIL="****@example.com"
PASSWORD="****"
#
aws cognito-idp admin-initiate-auth \
	--user-pool-id ${USER_POOL_ID} \
	--client-id ${CLIENT_ID} \
	--auth-flow ADMIN_NO_SRP_AUTH \
	--auth-parameters "USERNAME=${USER_EMAIL},PASSWORD=${PASSWORD}" > token.json
#

curl で AppSync にアクセス

client_user_pools.sh
API_URL="https://*****.appsync-api.ap-northeast-1.amazonaws.com/graphql"
#
JWT=`jq -r .AuthenticationResult.IdToken token.json`
#
curl -XPOST \
       -H "Content-Type:application/graphql" \
       -H "Authorization:"${JWT} \
        -d '{ "query": "query  { getUsers { items { id name email } } }" }' \
        ${API_URL}
#

Httpie で AppSync にアクセス

httpie_user_pools.sh
API_URL="https://*****.appsync-api.ap-northeast-1.amazonaws.com/graphql"
#
JWT=`jq -r .AuthenticationResult.IdToken token.json`
#
http POST ${API_URL} "Authorization:"${JWT} \
	query="query {getUsers { items { id name email }}}"
#

Python3 で AppSync にアクセス

appsync_client.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#	appsync_client.py
#
#					  Feb/27/2022
#
# ------------------------------------------------------------------
import  sys
import  json
import  requests
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")

file_in = sys.argv[1]
with open(file_in) as ff:
	json_str = ff.read().strip()
dict_aa = json.loads(json_str)
access_token = dict_aa['AuthenticationResult']['IdToken']
#
url="https://*****.appsync-api.ap-northeast-1.amazonaws.com/graphql"
#
headers = {'Authorization': '{}'.format(access_token)}
#
query='{ \"query\": \"query { getUsers { items { id name email } } }\" }'
response = requests.post(url, headers=headers, data=query)
#
print(response.text)
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行スクリプト

./appsync_client.py token.json

Node.js で AppSync にアクセス

appsync_client.js
// ---------------------------------------------------------------
//	appsync_client.js
//
//					Feb/28/2022
//
// ---------------------------------------------------------------
'use strict'

import * as https from "https"
import fs from 'fs'

const file_json=process.argv[2]

const json_str = fs.readFileSync (file_json,'utf8')
const dict_aa = JSON.parse (json_str)
const access_token = dict_aa['AuthenticationResult']['IdToken']

const query = "query { getUsers { items { id name email } } }"
const data = JSON.stringify({query: query})

const options = {
	method: "POST",
	headers: {
		"Content-Type": "application/json",
		'Content-Length': data.length,
		'Authorization': access_token
		}
}


const url="https://*****.appsync-api.ap-northeast-1.amazonaws.com/graphql"


const request = https.request(url, options, response => {
	console.error(`statusCode: ${response.statusCode}`)
response.on('data', (dd) => {
	process.stdout.write(dd)
	})
})

request.write(data)
request.end()


// ---------------------------------------------------------------
package.json
{
  "type": "module"
}

実行スクリプト

node ./appsync_client.js token.json

TypeScript で AppSync にアクセス

appsync_client.ts
// ---------------------------------------------------------------
//	appsync_client.ts
//
//					Feb/28/2022
//
// ---------------------------------------------------------------
const axios = require('axios')
const fs = require("fs")

console.error("*** 開始 ***")

const file_json=process.argv[2]

const json_str = fs.readFileSync (file_json,'utf8')
const dict_aa = JSON.parse (json_str)
const access_token = dict_aa['AuthenticationResult']['IdToken']

const url="https://*****.appsync-api.ap-northeast-1.amazonaws.com/graphql"


const query = "query { getUsers { items { id name email } } }"
const data = JSON.stringify({query: query})

const headers = {
	headers: {
		"Content-Type": "application/json",
		"Authorization": access_token
		},
}

axios.post(url, data,headers)
	.then(function (response: any) {
		console.log(JSON.stringify(response.data))
		})
	.catch(function (error: any) {
		console.log(error)
  		})
	.then(function () {
		console.error("*** 終了 ***")
		})

// ---------------------------------------------------------------

実行スクリプト

export NODE_PATH=/usr/lib/node_modules
#
ts-node appsync_client.ts token.json

Deno で AppSync にアクセス

appsync_client.ts
// ---------------------------------------------------------------
//	appsync_client.ts
//
//					Feb/28/2022
//
// ---------------------------------------------------------------
import ky from 'https://cdn.skypack.dev/ky?dts'
import { readFileStrSync } from "https://deno.land/std/fs/read_file_str.ts"

console.error ("*** 開始 ***")
const file_json: string = Deno.args[0]
console.error (file_json)

const json_str:string = readFileStrSync (file_json,{ encoding: "utf8" })
const dict_aa:{[key: string]: {[key: string]: any}}  = JSON.parse (json_str)
const access_token:string = dict_aa['AuthenticationResult']['IdToken']


const url="https://*****.appsync-api.ap-northeast-1.amazonaws.com/graphql"
const query = "query { getUsers { items { id name email } } }"

const data = {
	headers: {
		"Content-Type": "application/json",
		"Authorization": access_token
		},
	body: JSON.stringify({query: query})
}

const parsed = await ky.post(url, data).json()

console.log(JSON.stringify(parsed, null, 2))
 
console.error ("*** 終了 ***")
// ---------------------------------------------------------------

実行スクリプト

deno run --allow-read --allow-net appsync_client.ts token.json

Julia で AppSync にアクセス

appsync_client.jl
#! /usr/bin/julia
#
#	appsync_client.jl
#
#						Mar/02/2022
# --------------------------------------------------------------------
import Pkg; Pkg.add("HTTP")
using HTTP
using JSON
# --------------------------------------------------------------------
println(stderr,"*** 開始 ***")
file_json = ARGS[1]
println(stderr,file_json)
dict_aa = JSON.parsefile(file_json)
#
access_token = dict_aa["AuthenticationResult"]["IdToken"]
#
url = "https://*****.appsync-api.ap-northeast-1.amazonaws.com/graphql"
header = [("Content-Type", "application/json"),("Authorization", access_token)]
const query = "query { getUsers { items { id name email } } }"
params = Dict("query" => query)
#
rr = HTTP.request("POST",url,header,JSON.json(params))
#
println(stderr,rr.status)
println(String(rr.body))
println(stderr,"*** 終了 ***")
# --------------------------------------------------------------------

実行スクリプト

./appsync_client.jl token.json

参考

IdToken を Node.js で取得する方法はこちら
Node.js: Cognito から Access Token を取得

IdToken を Python3 で取得する方法はこちら
Python3: Cognito から Access Token を取得

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?