Skip to content

Instantly share code, notes, and snippets.

@matmunn
Last active February 17, 2022 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matmunn/c64a43dd10bc29c2f8dffa67a7f8b91f to your computer and use it in GitHub Desktop.
Save matmunn/c64a43dd10bc29c2f8dffa67a7f8b91f to your computer and use it in GitHub Desktop.
Cognito ID Token Fetcher

Cognito ID Token Fetcher

This is a deno helper script that can fetch a user's ID Token used for accessing resources protected by AWS Cognito.

To run:

deno run --unstable --allow-env --allow-read --allow-net https://gist.githubusercontent.com/matmunn/c64a43dd10bc29c2f8dffa67a7f8b91f/raw/0e766f98fe05c656e3661c28929142abb96f25f7/cognito-helper.ts <aws_region> <aws_cognito_client_id>

<aws_region> and <aws_cognito_client_id> can be supplied as environmental variables - AWS_REGION and AWS_COGNITO_CLIENT_ID respectively.

import yargs from 'https://deno.land/x/yargs/deno.ts'
import Ask from "https://deno.land/x/ask@1.0.6/mod.ts"
import { CognitoIdentityProvider } from "https://deno.land/x/aws_sdk@v3.14.0.0/client-cognito-identity-provider/mod.ts"
import { hmac } from "https://denopkg.com/chiefbiiko/hmac/mod.ts";
const args = yargs(Deno.args)
.usage(
"$0 <region> <cognito_client_id> [cognito_client_secret]",
'Authenticates against your AWS Cognito user pool and returns an access token.',
(yargs: any) => {
yargs
.positional("cognito_client_id", {
default: Deno.env.get("AWS_COGNITO_CLIENT_ID"),
describe: 'Cognito client ID (required)',
})
.positional("region", {
default: Deno.env.get("AWS_REGION"),
describe: 'AWS region ID (required)',
})
.option("cognit_client_secret", {
describe: "Cognito client secret",
})
}
)
.help()
.parse()
const ask = new Ask();
const loginQuestions = [
{
name: 'username',
message: 'Username:',
},
{
name: 'password',
message: 'Password:',
},
]
const answers = await ask.prompt(loginQuestions)
const { username, password } = answers
const {
cognito_client_id: cognitoClientId,
cognito_client_secret: cognitoClientSecret,
region
} = args
const cognitoClient = new CognitoIdentityProvider({
region,
})
type AuthOptions = {
AuthFlow: string,
ClientId: string,
AuthParameters: {[key: string]: string},
}
const authOpts: AuthOptions = {
AuthFlow: "USER_PASSWORD_AUTH",
ClientId: cognitoClientId,
AuthParameters: {
'USERNAME': username as string,
'PASSWORD': password as string,
},
}
if (cognitoClientSecret) {
authOpts.AuthParameters.SECRET_HASH = hmac("sha256", cognitoClientSecret, username as string + cognitoClientId, "utf8", "base64") as string
}
const response = await cognitoClient.initiateAuth(authOpts!)
console.log(response!.AuthenticationResult!.IdToken)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment