Skip to content

Instantly share code, notes, and snippets.

@justindav1s
Last active December 22, 2023 14:13
Show Gist options
  • Save justindav1s/7acedea1e4f1678f13c46db811b92134 to your computer and use it in GitHub Desktop.
Save justindav1s/7acedea1e4f1678f13c46db811b92134 to your computer and use it in GitHub Desktop.
#!/bin/bash
# This script requires jq, a command line to to parse and format JSon.
# https://stedolan.github.io/jq/
function padBase64 {
STR=$1
MOD=$((${#STR}%4))
if [ $MOD -eq 1 ]; then
STR="${STR}="
elif [ $MOD -gt 1 ]; then
STR="${STR}=="
fi
echo ${STR}
}
KEYCLOAK=http://127.0.0.1:8080
REALM="demo"
GRANT_TYPE="password"
CLIENT="tpp1"
CLIENT_SECRET="b38eae9d-d5ef-4a98-b1e6-6b5084b09d91"
USER="test_user2"
USER_PASSWORD="123456"
echo "Keycloak host : $KEYCLOAK"
echo "Token URL : ${KEYCLOAK}/auth/realms/${REALM}/protocol/openid-connect/token"
#Get Token
POST_BODY="grant_type=${GRANT_TYPE}&client_id=${CLIENT}&client_secret=${CLIENT_SECRET}&username=${USER}&password=${USER_PASSWORD}"
echo POST_BODY=${POST_BODY}
RESPONSE=$(curl -k \
-d ${POST_BODY} \
-H "Content-Type: application/x-www-form-urlencoded" \
${KEYCLOAK}/auth/realms/${REALM}/protocol/openid-connect/token)
echo "RESPONSE"=${RESPONSE}
ACCESS_TOKEN=$(echo ${RESPONSE} | jq -r .access_token)
PART1_BASE64=$(echo ${ACCESS_TOKEN} | cut -d"." -f1)
PART1_BASE64=$(padBase64 ${PART1_BASE64})
echo "HEADER"
echo $(echo ${PART1_BASE64} | base64 -D)
PART2_BASE64=$(echo ${ACCESS_TOKEN} | cut -d"." -f2)
PART2_BASE64=$(padBase64 ${PART2_BASE64})
echo
echo "PAYLOAD"
echo $(echo ${PART2_BASE64} | base64 -D | jq .)
HEADERPAYLOAD_BASE64=$(echo ${ACCESS_TOKEN} | cut -d"." -f1-2)
echo -n $HEADERPAYLOAD_BASE64 > HEADERPAYLOAD_BASE64.txt
PART3_BASE64=$(echo ${ACCESS_TOKEN} | cut -d"." -f3)
PART3_BASE64=$(padBase64 ${PART3_BASE64})
echo -n $PART3_BASE64 \
| perl -ne 'tr|-_|+/|; print "$1\n" while length>76 and s/(.{0,76})//; print' \
| openssl enc -base64 -d > sig.dat
echo
#Get Public Key
REALM_URL=${KEYCLOAK}/auth/realms/${REALM}
PUBLIC_KEY=$(curl -k $REALM_URL | jq -r .public_key)
PUBLIC_KEY=$(echo -n $PUBLIC_KEY | perl -ne 'tr|-_|+/|; print "$1\n" while length>76 and s/(.{0,76})//; print')
cat <<EOF > key.pem
-----BEGIN PUBLIC KEY-----
$PUBLIC_KEY
-----END PUBLIC KEY-----
EOF
#Perform Validation
openssl dgst -sha256 -verify key.pem -signature sig.dat HEADERPAYLOAD_BASE64.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment