diff options
| author | Shulhan <ms@kilabit.info> | 2022-09-18 03:16:20 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2022-09-18 03:21:14 +0700 |
| commit | c5214428f873ea124eb848a14907ac7a6dd210aa (patch) | |
| tree | 3241b4d1a0cac56d076778c3ae5b7b912054416b /bin | |
| parent | 15ba9c8fb84094744288c84b1d1cdc1bb8d33096 (diff) | |
| download | bin.sh-c5214428f873ea124eb848a14907ac7a6dd210aa.tar.xz | |
all: add script jwt-decode.sh
The script decode JWT with optional secret to check for signature.
Diffstat (limited to 'bin')
| -rwxr-xr-x | bin/jwt-decode.sh | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/bin/jwt-decode.sh b/bin/jwt-decode.sh new file mode 100755 index 0000000..5e47adf --- /dev/null +++ b/bin/jwt-decode.sh @@ -0,0 +1,73 @@ +#!/bin/sh +## SPDX-FileCopyrightText: 2022 M. Shulhan <ms@kilabit.info> +## SPDX-License-Identifier: GPL-3.0-or-later + +## depends=(jq openssl) + +## Script to decode JWT. +## +## Usage: +## +## $ jwt_decode.sh $token [$secret] +## +## The $secret argument is optional, if its given it will check the signature +## is matched or not. + +base64_decode() { + len=$((${#1} % 4)) + case $len in + 2) + str="$1"'==' ;; + 3) + str="$1"'=' ;; + *) + str="$1" ;; + esac + echo -n $str | openssl enc -d -a -A +} + +jwt=$1 +secret=$2 + +if [[ -z $jwt ]]; then + echo "Missing token" + exit 1 +fi + +header_b64=$(echo -n $jwt | cut -d '.' -f 1) +header=$(base64_decode "$header_b64") + +payload_b64=$(echo -n $jwt | cut -d '.' -f 2) +payload=$(base64_decode "$payload_b64") + +sign=$(echo -n $jwt | cut -d '.' -f 3) + +expired_at=$(echo $PAY | jq '.exp') +if [[ -n "$expired_at" ]]; then + expired_at=$(date -d @${expired_at} --rfc-3339=seconds) +fi + +issued_at=$(echo $PAY | jq '.iat') +if [[ -n "$issued_at" ]]; then + issued_at=$(date -d @${issued_at} --rfc-3339=seconds) +fi + +echo "Header: $header" +echo "Payload: $payload" +echo "Issued at: $issued_at" +echo "Expired at: $expired_at" + +## Check the signature using secret. +if [[ -n "$secret" ]]; then + got_sign=$(echo -n "$header_b64"."$payload_b64" \ + | openssl dgst -sha256 -hmac secret -binary | base64) + got_sign=${got_sign%=} + + if [[ "$sign" == "$got_sign" ]]; then + echo "Signature: PASS" + else + echo "Signature: FAIL" + fi +else + echo "Signature: SKIP" +fi |
