From c654ea51e1b20fdd4215fd8bcaa4db750eb56e50 Mon Sep 17 00:00:00 2001 From: benfdking Date: Sun, 14 Jun 2020 21:39:30 +0100 Subject: [PATCH] Add ability to specify local pem key --- cmd/jwt.go | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/cmd/jwt.go b/cmd/jwt.go index f1a9054..341f009 100644 --- a/cmd/jwt.go +++ b/cmd/jwt.go @@ -1,15 +1,19 @@ package cmd import ( + "crypto" "fmt" + "io/ioutil" "log" "github.com/benfdking/jen/pkg/defaultjwt" + "github.com/benfdking/jen/pkg/rsapem" "github.com/benfdking/jen/pkg/url" "github.com/spf13/cobra" ) var key string +var keyFilePath string var addDefaults bool var filePath string var claims map[string]string @@ -20,38 +24,55 @@ var jwtCmd = &cobra.Command{ Short: "Generate a jwt", Args: cobra.RangeArgs(0, 1), Run: func(cmd *cobra.Command, args []string) { - _, pem, err := url.ReturnJWKSAndPrivateKey(key) - if err != nil { - log.Fatal(err) + var privateKey crypto.PrivateKey + if keyFilePath != "" { + keyBytes, err := ioutil.ReadFile(keyFilePath) + if err != nil { + log.Fatal(err) + } + privateKey, err = rsapem.RSAPrivateFromPen(keyBytes) + if err != nil { + log.Fatal(err) + } + } else { + var err error + _, privateKey, err = url.ReturnJWKSAndPrivateKey(key) + if err != nil { + log.Fatal(err) + } } token := defaultjwt.NewToken() if addDefaults { + var err error token, err = defaultjwt.AddDefaultClaims(token) if err != nil { log.Fatal(err) } } if filePath != "" { + var err error token, err = defaultjwt.AddJSONFileClaimsToToken(token, filePath) if err != nil { log.Fatal(err) } } if len(args) == 1 { + var err error token, err = defaultjwt.AddJSONStringClaimsToToken(token, args[0]) if err != nil { log.Fatal(err) } } if len(claims) > 0 { + var err error token, err = defaultjwt.AddMapClaimsToToken(token, claims) if err != nil { log.Fatal(err) } } - s, err := defaultjwt.SignToken(token, pem) + s, err := defaultjwt.SignToken(token, privateKey) if err != nil { log.Fatal(err) } @@ -66,4 +87,5 @@ func init() { jwtCmd.Flags().StringVarP(&key, "key", "k", "a", "[abc] jwt key to use") jwtCmd.Flags().BoolVarP(&addDefaults, "defaults", "d", true, "Add default claims") jwtCmd.Flags().StringVarP(&filePath, "file", "f", "", "Add claims from JSON file") + jwtCmd.Flags().StringVarP(&keyFilePath, "private", "p", "", "Use private key to sign jwt") }