站点更新:2018-03-27 15:37:33
This commit is contained in:
68
token/showtoken.go
Normal file
68
token/showtoken.go
Normal file
@@ -0,0 +1,68 @@
|
||||
// Copyright © 2018 ehlxr <ehlxr.me@gmail.com>
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
package token
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
|
||||
jwt "github.com/dgrijalva/jwt-go"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// showToken pretty-prints the token on the command line.
|
||||
func ShowToken(cmd *cobra.Command) error {
|
||||
flagToken := cmd.LocalFlags().Lookup("token").Value.String()
|
||||
flagDebug := promptDebug()
|
||||
flagCompact := promptCompact()
|
||||
|
||||
// get the token
|
||||
tokData, err := loadData(flagToken)
|
||||
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, flagCompact); err != nil {
|
||||
return fmt.Errorf("Failed to output header: %v", err)
|
||||
}
|
||||
|
||||
fmt.Println("Claims:")
|
||||
if err := printJSON(token.Claims, flagCompact); err != nil {
|
||||
return fmt.Errorf("Failed to output claims: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
122
token/signtoken.go
Normal file
122
token/signtoken.go
Normal file
@@ -0,0 +1,122 @@
|
||||
// Copyright © 2018 ehlxr <ehlxr.me@gmail.com>
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
package token
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/atotto/clipboard"
|
||||
|
||||
jwt "github.com/dgrijalva/jwt-go"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// Create, sign, and output a token. This is a great, simple example of
|
||||
// how to use this library to create and sign a token.
|
||||
func SignToken(cmd *cobra.Command) error {
|
||||
flagData := cmd.LocalFlags().Lookup("data").Value.String()
|
||||
flagClaims := cmd.LocalFlags().Lookup("claims").Value.(ArgList)
|
||||
flagHead := cmd.LocalFlags().Lookup("header").Value.(ArgList)
|
||||
flagKey := cmd.LocalFlags().Lookup("key").Value.String()
|
||||
flagDebug := promptDebug()
|
||||
|
||||
flagAlg, err := promptAlg()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Prompt flagAlg failed %v\n", err)
|
||||
}
|
||||
|
||||
// get the token data from command line arguments
|
||||
tokData, err := loadData(flagData)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Couldn't read data: %v", err)
|
||||
} else if flagDebug {
|
||||
fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData))
|
||||
fmt.Fprintf(os.Stderr, "Token data: %v \n", string(tokData))
|
||||
}
|
||||
|
||||
// parse the JSON of the claims
|
||||
var claims jwt.MapClaims
|
||||
if err := json.Unmarshal(tokData, &claims); err != nil {
|
||||
return fmt.Errorf("Couldn't parse claims JSON: %v", err)
|
||||
}
|
||||
|
||||
// add command line claims
|
||||
if len(flagClaims) > 0 {
|
||||
for k, v := range flagClaims {
|
||||
claims[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
// get the key
|
||||
var key interface{}
|
||||
key, err = loadData(flagKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Couldn't read key: %v", err)
|
||||
}
|
||||
|
||||
// get the signing alg
|
||||
alg := jwt.GetSigningMethod(flagAlg)
|
||||
if alg == nil {
|
||||
return fmt.Errorf("Couldn't find signing method alg: %v", flagAlg)
|
||||
}
|
||||
|
||||
// create a new token
|
||||
token := jwt.NewWithClaims(alg, claims)
|
||||
|
||||
// add command line headers
|
||||
if len(flagHead) > 0 {
|
||||
for k, v := range flagHead {
|
||||
token.Header[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
if isEs(flagAlg) {
|
||||
if k, ok := key.([]byte); !ok {
|
||||
return fmt.Errorf("Couldn't convert key data to key")
|
||||
} else {
|
||||
key, err = jwt.ParseECPrivateKeyFromPEM(k)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else if isRs(flagAlg) {
|
||||
if k, ok := key.([]byte); !ok {
|
||||
return fmt.Errorf("Couldn't convert key data to key")
|
||||
} else {
|
||||
key, err = jwt.ParseRSAPrivateKeyFromPEM(k)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if out, err := token.SignedString(key); err == nil {
|
||||
fmt.Println(out)
|
||||
clipboard.WriteAll(out)
|
||||
} else {
|
||||
return fmt.Errorf("Error signing token: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
163
token/token.go
Normal file
163
token/token.go
Normal file
@@ -0,0 +1,163 @@
|
||||
// Copyright © 2018 ehlxr <ehlxr.me@gmail.com>
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
package token
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/atotto/clipboard"
|
||||
|
||||
"github.com/manifoldco/promptui"
|
||||
)
|
||||
|
||||
// Helper func: Read input from specified file or string
|
||||
func loadData(p string) ([]byte, error) {
|
||||
if p == "" {
|
||||
return nil, fmt.Errorf("No path or arg specified")
|
||||
}
|
||||
|
||||
var rdr io.Reader
|
||||
if p == "-" {
|
||||
t, _ := clipboard.ReadAll()
|
||||
fmt.Printf("read data from clipboard: %s\n", t)
|
||||
rdr = strings.NewReader(t)
|
||||
} else if p == "+" {
|
||||
return []byte("{}"), nil
|
||||
} else {
|
||||
is, path := isPath(p)
|
||||
if is {
|
||||
if f, err := os.Open(path); err == nil {
|
||||
rdr = f
|
||||
defer f.Close()
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
rdr = strings.NewReader(p)
|
||||
}
|
||||
}
|
||||
return ioutil.ReadAll(rdr)
|
||||
}
|
||||
|
||||
func isPath(path string) (bool, string) {
|
||||
p, err := filepath.Abs("")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
absPath := filepath.Join(p, strings.Replace(path, p, "", 1))
|
||||
_, err = os.Stat(absPath)
|
||||
if err == nil {
|
||||
return true, absPath
|
||||
}
|
||||
return false, ""
|
||||
}
|
||||
|
||||
// Print a json object in accordance with the prophecy (or the command line options)
|
||||
func printJSON(j interface{}, flagCompact bool) error {
|
||||
var out []byte
|
||||
var err error
|
||||
|
||||
if flagCompact == false {
|
||||
out, err = json.MarshalIndent(j, "", " ")
|
||||
} else {
|
||||
out, err = json.Marshal(j)
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
fmt.Println(string(out))
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func isEs(flagAlg string) bool {
|
||||
return strings.HasPrefix(flagAlg, "ES")
|
||||
}
|
||||
|
||||
func isRs(flagAlg string) bool {
|
||||
return strings.HasPrefix(flagAlg, "RS")
|
||||
}
|
||||
|
||||
func promptAlg() (string, error) {
|
||||
prompt := promptui.SelectWithAdd{
|
||||
Label: "select a signing algorithm identifier",
|
||||
Items: []string{"HS256", "RS256"},
|
||||
AddLabel: "Other",
|
||||
}
|
||||
_, flagAlg, err := prompt.Run()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("Prompt flagAlg failed %v\n", err)
|
||||
}
|
||||
|
||||
return flagAlg, nil
|
||||
}
|
||||
|
||||
func promptDebug() bool {
|
||||
prompt := promptui.Prompt{
|
||||
Label: "print out all kinds of debug data",
|
||||
IsConfirm: true,
|
||||
}
|
||||
|
||||
if _, err := prompt.Run(); err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func promptCompact() bool {
|
||||
prompt := promptui.Prompt{
|
||||
Label: "output compact JSON",
|
||||
IsConfirm: true,
|
||||
}
|
||||
|
||||
if _, err := prompt.Run(); err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type ArgList map[string]string
|
||||
|
||||
func (l ArgList) String() string {
|
||||
data, _ := json.Marshal(l)
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func (l ArgList) Set(arg string) error {
|
||||
parts := strings.SplitN(arg, "=", 2)
|
||||
if len(parts) != 2 {
|
||||
return fmt.Errorf("Invalid argument '%v'. Must use format 'key=value'. %v", arg, parts)
|
||||
}
|
||||
l[parts[0]] = parts[1]
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l ArgList) Type() string {
|
||||
return "argList"
|
||||
}
|
93
token/verifytoken.go
Normal file
93
token/verifytoken.go
Normal file
@@ -0,0 +1,93 @@
|
||||
// Copyright © 2018 ehlxr <ehlxr.me@gmail.com>
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
package token
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
|
||||
jwt "github.com/dgrijalva/jwt-go"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// Verify a token and output the claims. This is a great example
|
||||
// of how to verify and view a token.
|
||||
func VerifyToken(cmd *cobra.Command) error {
|
||||
flagToken := cmd.LocalFlags().Lookup("token").Value.String()
|
||||
flagKey := cmd.LocalFlags().Lookup("key").Value.String()
|
||||
flagCompact := promptCompact()
|
||||
flagDebug := promptDebug()
|
||||
|
||||
flagAlg, err := promptAlg()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Prompt flagAlg failed %v\n", err)
|
||||
}
|
||||
|
||||
// get the token
|
||||
tokData, err := loadData(flagToken)
|
||||
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))
|
||||
}
|
||||
|
||||
// Parse the token. Load the key from command line option
|
||||
token, err := jwt.Parse(string(tokData), func(t *jwt.Token) (interface{}, error) {
|
||||
data, err := loadData(flagKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if isEs(flagAlg) {
|
||||
return jwt.ParseECPublicKeyFromPEM(data)
|
||||
} else if isRs(flagAlg) {
|
||||
return jwt.ParseRSAPublicKeyFromPEM(data)
|
||||
}
|
||||
return data, nil
|
||||
})
|
||||
|
||||
// Print some debug data
|
||||
if flagDebug && token != nil {
|
||||
fmt.Fprintf(os.Stderr, "Header:\n%v\n", token.Header)
|
||||
fmt.Fprintf(os.Stderr, "Claims:\n%v\n", token.Claims)
|
||||
}
|
||||
|
||||
// Print an error if we can't parse for some reason
|
||||
if err != nil {
|
||||
return fmt.Errorf("Couldn't parse token: %v", err)
|
||||
}
|
||||
|
||||
// Is token invalid?
|
||||
if !token.Valid {
|
||||
return fmt.Errorf("Token is invalid")
|
||||
}
|
||||
|
||||
// Print the token details
|
||||
if err := printJSON(token.Claims, flagCompact); err != nil {
|
||||
return fmt.Errorf("Failed to output claims: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
Reference in New Issue
Block a user