-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
96 lines (91 loc) · 2.23 KB
/
main.go
File metadata and controls
96 lines (91 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"fmt"
"github.com/codegangsta/cli"
jwt "github.com/dgrijalva/jwt-go"
"io/ioutil"
"os"
"path/filepath"
)
func main() {
app := cli.NewApp()
app.Name = "MicroBay CLI"
app.Usage = "CLI for MicroBay API gateway"
app.Action = func(c *cli.Context) {
println("Welcome to " + app.Name + ". Type 'cli help'")
}
app.Commands = []cli.Command{
{
Name: "token",
Aliases: []string{"t"},
Usage: "JWT access token base command",
Subcommands: []cli.Command{
{
Name: "sign",
Usage: "sign a token",
Flags: []cli.Flag{
cli.StringFlag{
Name: "key, k",
Value: "",
Usage: "private key file",
},
},
Action: func(c *cli.Context) {
keyPath, _ := filepath.Abs(c.String("key"))
key, err := ioutil.ReadFile(keyPath)
if err != nil {
println("Failed loading private key file", keyPath, err)
return
}
token := jwt.New(jwt.SigningMethodHS256)
token.Claims["foo"] = "bar"
tokenString, err := token.SignedString(key)
if err != nil {
println("Failed creating token", err)
} else {
println(tokenString)
}
},
},
{
Name: "verify",
Usage: "verfiy a token",
Flags: []cli.Flag{
cli.StringFlag{
Name: "token, t",
Value: "",
Usage: "JWT token",
},
cli.StringFlag{
Name: "key, k",
Value: "",
Usage: "public key",
},
},
Action: func(c *cli.Context) {
input := c.String("token")
keyPath, _ := filepath.Abs(c.String("key"))
key, err := ioutil.ReadFile(keyPath)
if err != nil {
println("Failed loading public key file", keyPath, err)
return
}
token, err := jwt.Parse(input, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return key, nil
})
if err == nil && token.Valid {
println("Successfuly verfied token", input)
} else {
println("Failed", err)
}
},
},
},
},
}
app.Run(os.Args)
}