Last active
July 8, 2022 11:16
-
-
Save rolandyoung/176dd310a6948e094be6 to your computer and use it in GitHub Desktop.
Using openssl to verify a JWT from Keycloak
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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'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
little bit simpler script
https://gist.github.com/stokito/f2d7ea0b300f14638a9063559384ec89