Skip to content

Instantly share code, notes, and snippets.

@wvanderdeijl
Created March 30, 2021 14:42
Show Gist options
  • Save wvanderdeijl/7b5c3a8d850ea1096cac8f5335ee294d to your computer and use it in GitHub Desktop.
Save wvanderdeijl/7b5c3a8d850ea1096cac8f5335ee294d to your computer and use it in GitHub Desktop.
Temporary AWS credentials from AWS Cognito Identity Pool (using Cognito User Pool)
export USR=xxxxxxxx
export PWD=xxxxxxxx
export COGNITO_CLIENT_ID=40qxxxxxxxxxxxxxxxxxxxxn40
# 12 digit numeric AWS account id
export AWS_ACCOUNT_ID=765000000630
export AWS_REGION=eu-central-1
export IDENTITY_POOL_GUID=e14xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxd89
export USER_POOL_ID=eu-central-1_oYTxxxxov
# sign in with username/password
export IDTOKEN=$(aws cognito-idp initiate-auth --region eu-central-1 \
--auth-flow USER_PASSWORD_AUTH --auth-parameters "USERNAME=$USR,PASSWORD=$PWD" \
--client-id $COGNITO_CLIENT_ID | jq -r '.AuthenticationResult.IdToken')
# get id for "my" identity from identity pool
export IDENTITY_ID=$(aws cognito-identity get-id \
--account-id $AWS_ACCOUNT_ID \
--region $AWS_REGION \
--identity-pool-id "$AWS_REGION:$IDENTITY_POOL_GUID" \
--logins cognito-idp.$AWS_REGION.amazonaws.com/$USER_POOL_ID=$IDTOKEN | jq -r '.IdentityId')
# get temporary credentials for identity
export AWS_TEMP_CREDS=$(aws cognito-identity get-credentials-for-identity --identity-id $IDENTITY_ID \
--region $AWS_REGION \
--logins cognito-idp.$AWS_REGION.amazonaws.com/$USER_POOL_ID=$IDTOKEN | jq -r '.Credentials')
echo "AWS_ACCESS_KEY_ID=$(echo $AWS_TEMP_CREDS | jq -r '.AccessKeyId')"
echo "AWS_SECRET_ACCESS_KEY=$(echo $AWS_TEMP_CREDS | jq -r '.SecretKey')"
echo "AWS_SESSION_TOKEN=$(echo $AWS_TEMP_CREDS | jq -r '.SessionToken')"
# get caller identity to see if temp credentials work
AWS_ACCESS_KEY_ID=$(echo $AWS_TEMP_CREDS | jq -r '.AccessKeyId') \
AWS_SECRET_ACCESS_KEY=$(echo $AWS_TEMP_CREDS | jq -r '.SecretKey') \
AWS_SESSION_TOKEN=$(echo $AWS_TEMP_CREDS | jq -r '.SessionToken') \
aws sts get-caller-identity
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment