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

こちらのサンプルの認証モードを
API KEY から、COGNITO_USER_POOLS にした時の使い方です。
[AWS: AppSync の使い方](https://qiita.com/ekzemplaro/items/d7ecf3e7846c3f30a2b3)

## IdToken (JWT) の取得 ##

```bash: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 にアクセス ##

```bash: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 にアクセス ##

```bash: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 にアクセス ##

```py: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")
# ------------------------------------------------------------------
```

実行スクリプト

```bash
./appsync_client.py token.json
```

## Node.js で AppSync にアクセス ##

```js: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()


// ---------------------------------------------------------------
```

```json:package.json
{
  "type": "module"
}
```

実行スクリプト

```bash
node ./appsync_client.js token.json
```

## TypeScript で AppSync にアクセス ##

```ts: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("*** 終了 ***")
		})

// ---------------------------------------------------------------
```

実行スクリプト

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

## Deno で AppSync にアクセス ##

```ts: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 ("*** 終了 ***")
// ---------------------------------------------------------------
```

実行スクリプト

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

## Julia で AppSync にアクセス ##

```julia: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,"*** 終了 ***")
# --------------------------------------------------------------------
```

実行スクリプト

```bash
./appsync_client.jl token.json
```

## 参考 ##
IdToken を Node.js で取得する方法はこちら
[Node.js: Cognito から Access Token を取得](https://qiita.com/ekzemplaro/items/a0ec95868721c8279500)

IdToken を Python3 で取得する方法はこちら
[Python3: Cognito から Access Token を取得](https://qiita.com/ekzemplaro/items/65cb1b33c5007c802c21)