Skip to content

Instantly share code, notes, and snippets.

@raupachz
Last active July 3, 2023 15:38
Show Gist options
  • Save raupachz/c0edcd2c8f90231725c8cb129e2d34be to your computer and use it in GitHub Desktop.
Save raupachz/c0edcd2c8f90231725c8cb129e2d34be to your computer and use it in GitHub Desktop.
Amazon Cognito User Pools - SecretHash computation with OpenSSL

If your Amazon Cognito User Pool is configured with a Secret you need to append a SecretHash to the API's query argument. Otherwise you end up with error messages.

An error occurred (NotAuthorizedException) when calling the InitiateAuth operation: Client examplefoobar is configured for secret but secret was not received

Unfortunately the AWS Command Line Interface is unable to compute the SecretHash for you. Instead they provide you with a Python Script to do the computation for you.

You can also compute the SecretHash with OpenSSL. I do this in Bash Scripts. For example here is a little script to compute the access token for a user in a user pool.

USERNAME=<cognito user pool username>
CLIENT_ID=<your client_id>
CLIENT_SECRET=<your client secret>

SECRET_HASH=$(echo -n $USERNAME$CLIENT_ID | openssl sha256 -binary -mac HMAC -macopt key:$CLIENT_SECRET | base64)

RESPONSE=$(aws cognito-idp initiate-auth      \
  --client-id $CLIENT_ID                 \
  --auth-flow USER_PASSWORD_AUTH   \
  --auth-parameters USERNAME=$USERNAME,PASSWORD="$PASSWORD",SECRET_HASH=$SECRET_HASH)

if [ $? -ne 0 ]; then
  echo invalid credentials
  exit 1
fi

ACCESS_TOKEN=$(echo $RESPONSE | jq -r '.AuthenticationResult.AccessToken')

References:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment