Last active
April 30, 2024 17:09
-
-
Save angelo-v/e0208a18d455e2e6ea3c40ad637aac53 to your computer and use it in GitHub Desktop.
Decode a JWT via command line
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
# will not work in all cases, see https://gist.github.com/angelo-v/e0208a18d455e2e6ea3c40ad637aac53#gistcomment-3439904 | |
function jwt-decode() { | |
sed 's/\./\n/g' <<< $(cut -d. -f1,2 <<< $1) | base64 --decode | jq | |
} | |
JWT=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ | |
jwt-decode $JWT |
Or an universal GO approach using RawStdEncoding (with temporary file):
cat << EOFT > ./temp.go && go run ./temp.go $JWT |jq '.|select(.type=="wrapping")' ; rm ./temp.go
package main
import (
"encoding/base64"
"strings"
"fmt"
"os"
)
var encoded = os.Args[1]
func main() {
split := strings.Split(encoded, ".")
for i := 0; i < len(split); i++ {
tokenBytes, err := base64.RawStdEncoding.DecodeString(split[i])
if err != nil {
return
}
var sToken=string(tokenBytes)
fmt.Printf("%s",sToken)
}
}
EOFT
With just jq:
jq -R 'split(".") | .[1] | @base64d | fromjson' <<< "$JWT"
Excellent solution, thanks @lukaslihotzki
What about echo "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ" | cut -d '.' -f 2 | base64 -d
what about basenc
it's part of coreutils ?
basenc -d --base64url -i <your_file> | jq
Sure; coreutils 8.31 and newer, so was not in stable OS releases at the time of the gist. Today, I'd recommend basenc.
Oh, beware though that basenc
complains about missing =
signs, even in --base64url
mode, so you'll also need to suppress stderr.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @lukaslihotzki, very useful!