Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using openssl to verify a JWT from Keycloak
#!/bin/bash
# tested with OpenSSL 1.0.1e-fips on Centos 6
# Note hardcoded Keycloak URL and credentials.
# Keycloak public key is in ATS-ci.key.pem with -----BEGIN PUBLIC KEY----- (etc)
assert() { if [[ $1 != $2 ]]; then echo "assert" $3; exit; fi }
url=http://192.168.10.221:8088/auth/realms/ATS-ci/protocol/openid-connect/token
resp=$(curl -X POST $url \
--data "username=ats1" --data "password=xxx" --data "client_id=geneos-client" \
--data "grant_type=password" 2> err.log)
if [[ $? -eq 0 ]]; then rm err.log; else cat err.log; exit; fi
# echo $resp > message.txt
# resp=$(cat message.txt)
resp=${resp%%?,?expires_in*}
jwt=${resp#*token?:?}
echo JWT:
echo $jwt
input=${jwt%.*}
encHdr=${input%.*}
encPayload=${input#*.}
encSig=${jwt##*.}
assert $jwt "$encHdr.$encPayload.$encSig" "failed to decompose jwt"
echo Header:
echo $encHdr | openssl enc -base64 -d
echo
echo Payload:
echo -n $encPayload \
| perl -ne 'tr|-_|+/|; print "$1\n" while length>76 and s/(.{0,76})//; $_ .= ("", "", "==", "=")[length($_) % 4]; print' \
| openssl enc -base64 -d
echo
echo -n $encSig \
| perl -ne 'tr|-_|+/|; print "$1\n" while length>76 and s/(.{0,76})//; $_ .= ("", "", "==", "=")[length($_) % 4]; print' \
| openssl enc -base64 -d > ATS-ci.sig.dat
echo -n $input > ATS-ci.input.txt
openssl dgst -sha256 -verify ATS-ci.key.pem -signature ATS-ci.sig.dat ATS-ci.input.txt
@stokito
Copy link

stokito commented Jan 21, 2020

@rolandyoung
Copy link
Author

rolandyoung commented Jan 21, 2020

@stokito's script is definitely easier to use. But if you need to avoid jq, you may be able to pick some useful tips out of mine :-)

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