Skip to content

Instantly share code, notes, and snippets.

@ku
Created May 16, 2024 09:19
Show Gist options
  • Save ku/a42cfd76aec7c0aa85d376c8a9c6be6f to your computer and use it in GitHub Desktop.
Save ku/a42cfd76aec7c0aa85d376c8a9c6be6f to your computer and use it in GitHub Desktop.
decode and print claims in JWT
package main
import (
"encoding/base64"
"fmt"
"io"
"os"
"strings"
"golang.org/x/term"
)
func main() {
var jwtString string
if term.IsTerminal(int(os.Stdin.Fd())) {
if len(os.Args) < 2 {
println("usage:\n claims <base64 encoded JWT>")
}
jwtString = os.Args[1]
} else {
// read from stdin
b, err := io.ReadAll(os.Stdin)
if err != nil {
fmt.Printf("failed to read from stdin: %s", err.Error())
}
jwtString = string(b)
}
if err := decode(jwtString); err != nil {
println(err.Error())
}
}
func decode(jwtString string) error {
components := strings.Split(jwtString, ".")
if len(components) < 3 {
return fmt.Errorf("string has only %d components. %s", len(components), jwtString)
}
b, err := base64.RawURLEncoding.DecodeString(components[1])
if err != nil {
return fmt.Errorf("base64 decode: %w %s", err, components[1])
}
println(string(b))
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment