From 36ab8fba559509e8194d8041699fb5fdd33c88e8 Mon Sep 17 00:00:00 2001 From: Alexandre Bourget Date: Thu, 14 Apr 2016 14:25:22 -0400 Subject: [PATCH] Implement a "-show" command too.. for debugging purposes.. --- cmd/jwt/README.md | 13 +++++++++++++ cmd/jwt/app.go | 38 +++++++++++++++++++++++++++++++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 cmd/jwt/README.md diff --git a/cmd/jwt/README.md b/cmd/jwt/README.md new file mode 100644 index 0000000..4a68ba4 --- /dev/null +++ b/cmd/jwt/README.md @@ -0,0 +1,13 @@ +`jwt` command-line tool +======================= + +This is a simple tool to sign, verify and show JSON Web Tokens from +the command line. + +The following will create and sign a token, then verify it and output the original claims: + + echo {\"foo\":\"bar\"} | bin/jwt -key test/sample_key -alg RS256 -sign - | bin/jwt -key test/sample_key.pub -verify - + +To simply display a token, use: + + echo $JWT | jwt -show - diff --git a/cmd/jwt/app.go b/cmd/jwt/app.go index 4068a80..e8bc336 100644 --- a/cmd/jwt/app.go +++ b/cmd/jwt/app.go @@ -16,7 +16,7 @@ import ( "regexp" "strings" - "github.com/dgrijalva/jwt-go" + jwt "github.com/dgrijalva/jwt-go" ) var ( @@ -29,6 +29,7 @@ var ( // Modes - exactly one of these is required flagSign = flag.String("sign", "", "path to claims object to sign or '-' to read from stdin") flagVerify = flag.String("verify", "", "path to JWT token to verify or '-' to read from stdin") + flagShow = flag.String("show", "", "path to JWT file or '-' to read from stdin") ) func main() { @@ -56,6 +57,8 @@ func start() error { return signToken() } else if *flagVerify != "" { return verifyToken() + } else if *flagShow != "" { + return showToken() } else { flag.Usage() return fmt.Errorf("None of the required flags are present. What do you want me to do?") @@ -205,6 +208,39 @@ func signToken() error { return nil } +// showToken pretty-prints the token on the command line. +func showToken() error { + // get the token + tokData, err := loadData(*flagShow) + if err != nil { + return fmt.Errorf("Couldn't read token: %v", err) + } + + // trim possible whitespace from token + tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{}) + if *flagDebug { + fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData)) + } + + token, err := jwt.Parse(string(tokData), nil) + if token == nil { + return fmt.Errorf("malformed token: %v", err) + } + + // Print the token details + fmt.Println("Header:") + if err := printJSON(token.Header); err != nil { + return fmt.Errorf("Failed to output header: %v", err) + } + + fmt.Println("Claims:") + if err := printJSON(token.Claims); err != nil { + return fmt.Errorf("Failed to output claims: %v", err) + } + + return nil +} + func isEs() bool { return strings.HasPrefix(*flagAlg, "ES") }