Skip to content

Commit

Permalink
Merge pull request #33 from benfdking/26/add_ability_to_add_private_key
Browse files Browse the repository at this point in the history
Add ability to specify local pem key
benfdking authored Jun 14, 2020
2 parents 9d2b92f + c654ea5 commit 8007d92
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions cmd/jwt.go
Original file line number Diff line number Diff line change
@@ -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")
}

0 comments on commit 8007d92

Please sign in to comment.