Debian Codegraph @

cmd/jwt/main.go

raw
1 // A useful example app. You can use this to debug your tokens on the command line.
2 // This is also a great place to look at how you might use this library.
3 //
4 // Example usage:
5 // The following will create and sign a token, then verify it and output the original claims.
6 //
7 // echo {\"foo\":\"bar\"} | bin/jwt -key test/sample_key -alg RS256 -sign - | bin/jwt -key test/sample_key.pub -verify -
8 package main
9
10 import (
11 "encoding/json"
12 "flag"
13 "fmt"
14 "io"
15 "os"
16 "regexp"
17 "sort"
18 "strings"
19
20 "github.com/golang-jwt/jwt/v4"
21 )
22
23 var (
24 // Options
25 flagAlg = flag.String("alg", "", algHelp())
26 flagKey = flag.String("key", "", "path to key file or '-' to read from stdin")
27 flagCompact = flag.Bool("compact", false, "output compact JSON")
28 flagDebug = flag.Bool("debug", false, "print out all kinds of debug data")
29 flagClaims = make(ArgList)
30 flagHead = make(ArgList)
31
32 // Modes - exactly one of these is required
33 flagSign = flag.String("sign", "", "path to claims object to sign, '-' to read from stdin, or '+' to use only -claim args")
34 flagVerify = flag.String("verify", "", "path to JWT token to verify or '-' to read from stdin")
35 flagShow = flag.String("show", "", "path to JWT file or '-' to read from stdin")
36 )
37
38 func main() {
39 // Plug in Var flags
40 flag.Var(flagClaims, "claim", "add additional claims. may be used more than once")
41 flag.Var(flagHead, "header", "add additional header params. may be used more than once")
42
43 // Usage message if you ask for -help or if you mess up inputs.
44 flag.Usage = func() {
45 fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
46 fmt.Fprintf(os.Stderr, " One of the following flags is required: sign, verify\n")
47 flag.PrintDefaults()
48 }
49
50 // Parse command line options
51 flag.Parse()
52
53 // Do the thing. If something goes wrong, print error to stderr
54 // and exit with a non-zero status code
55 if err := start(); err != nil {
56 fmt.Fprintf(os.Stderr, "Error: %v\n", err)
57 os.Exit(1)
58 }
59 }
60
61 // Figure out which thing to do and then do that
62 func start() error {
63 if *flagSign != "" {
64 return signToken()
65 } else if *flagVerify != "" {
66 return verifyToken()
67 } else if *flagShow != "" {
68 return showToken()
69 } else {
70 flag.Usage()
71 return fmt.Errorf("none of the required flags are present. What do you want me to do?")
72 }
73 }
74
75 // Helper func: Read input from specified file or stdin
76 func loadData(p string) ([]byte, error) {
77 if p == "" {
78 return nil, fmt.Errorf("no path specified")
79 }
80
81 var rdr io.Reader
82 if p == "-" {
83 rdr = os.Stdin
84 } else if p == "+" {
85 return []byte("{}"), nil
86 } else {
87 if f, err := os.Open(p); err == nil {
88 rdr = f
89 defer f.Close()
90 } else {
91 return nil, err
92 }
93 }
94 return io.ReadAll(rdr)
95 }
96
97 // Print a json object in accordance with the prophecy (or the command line options)
98 func printJSON(j interface{}) error {
99 var out []byte
100 var err error
101
102 if !*flagCompact {
103 out, err = json.MarshalIndent(j, "", " ")
104 } else {
105 out, err = json.Marshal(j)
106 }
107
108 if err == nil {
109 fmt.Println(string(out))
110 }
111
112 return err
113 }
114
115 // Verify a token and output the claims. This is a great example
116 // of how to verify and view a token.
117 func verifyToken() error {
118 // get the token
119 tokData, err := loadData(*flagVerify)
120 if err != nil {
121 return fmt.Errorf("couldn't read token: %w", err)
122 }
123
124 // trim possible whitespace from token
125 tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{})
126 if *flagDebug {
127 fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData))
128 }
129
130 // Parse the token. Load the key from command line option
131 token, err := jwt.Parse(string(tokData), func(t *jwt.Token) (interface{}, error) {
132 if isNone() {
133 return jwt.UnsafeAllowNoneSignatureType, nil
134 }
135 data, err := loadData(*flagKey)
136 if err != nil {
137 return nil, err
138 }
139 if isEs() {
140 return jwt.ParseECPublicKeyFromPEM(data)
141 } else if isRs() {
142 return jwt.ParseRSAPublicKeyFromPEM(data)
143 } else if isEd() {
144 return jwt.ParseEdPublicKeyFromPEM(data)
145 }
146 return data, nil
147 })
148
149 // Print some debug data
150 if *flagDebug && token != nil {
151 fmt.Fprintf(os.Stderr, "Header:\n%v\n", token.Header)
152 fmt.Fprintf(os.Stderr, "Claims:\n%v\n", token.Claims)
153 }
154
155 // Print an error if we can't parse for some reason
156 if err != nil {
157 return fmt.Errorf("couldn't parse token: %w", err)
158 }
159
160 // Is token invalid?
161 if !token.Valid {
162 return fmt.Errorf("token is invalid")
163 }
164
165 // Print the token details
166 if err := printJSON(token.Claims); err != nil {
167 return fmt.Errorf("failed to output claims: %w", err)
168 }
169
170 return nil
171 }
172
173 // Create, sign, and output a token. This is a great, simple example of
174 // how to use this library to create and sign a token.
175 func signToken() error {
176 // get the token data from command line arguments
177 tokData, err := loadData(*flagSign)
178 if err != nil {
179 return fmt.Errorf("couldn't read token: %w", err)
180 } else if *flagDebug {
181 fmt.Fprintf(os.Stderr, "Token: %v bytes", len(tokData))
182 }
183
184 // parse the JSON of the claims
185 var claims jwt.MapClaims
186 if err := json.Unmarshal(tokData, &claims); err != nil {
187 return fmt.Errorf("couldn't parse claims JSON: %w", err)
188 }
189
190 // add command line claims
191 if len(flagClaims) > 0 {
192 for k, v := range flagClaims {
193 claims[k] = v
194 }
195 }
196
197 // get the key
198 var key interface{}
199 if isNone() {
200 key = jwt.UnsafeAllowNoneSignatureType
201 } else {
202 key, err = loadData(*flagKey)
203 if err != nil {
204 return fmt.Errorf("couldn't read key: %w", err)
205 }
206 }
207
208 // get the signing alg
209 alg := jwt.GetSigningMethod(*flagAlg)
210 if alg == nil {
211 return fmt.Errorf("couldn't find signing method: %v", *flagAlg)
212 }
213
214 // create a new token
215 token := jwt.NewWithClaims(alg, claims)
216
217 // add command line headers
218 if len(flagHead) > 0 {
219 for k, v := range flagHead {
220 token.Header[k] = v
221 }
222 }
223
224 if isEs() {
225 if k, ok := key.([]byte); !ok {
226 return fmt.Errorf("couldn't convert key data to key")
227 } else {
228 key, err = jwt.ParseECPrivateKeyFromPEM(k)
229 if err != nil {
230 return err
231 }
232 }
233 } else if isRs() {
234 if k, ok := key.([]byte); !ok {
235 return fmt.Errorf("couldn't convert key data to key")
236 } else {
237 key, err = jwt.ParseRSAPrivateKeyFromPEM(k)
238 if err != nil {
239 return err
240 }
241 }
242 } else if isEd() {
243 if k, ok := key.([]byte); !ok {
244 return fmt.Errorf("couldn't convert key data to key")
245 } else {
246 key, err = jwt.ParseEdPrivateKeyFromPEM(k)
247 if err != nil {
248 return err
249 }
250 }
251 }
252
253 if out, err := token.SignedString(key); err == nil {
254 fmt.Println(out)
255 } else {
256 return fmt.Errorf("error signing token: %w", err)
257 }
258
259 return nil
260 }
261
262 // showToken pretty-prints the token on the command line.
263 func showToken() error {
264 // get the token
265 tokData, err := loadData(*flagShow)
266 if err != nil {
267 return fmt.Errorf("couldn't read token: %w", err)
268 }
269
270 // trim possible whitespace from token
271 tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{})
272 if *flagDebug {
273 fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData))
274 }
275
276 token, err := jwt.Parse(string(tokData), nil)
277 if token == nil {
278 return fmt.Errorf("malformed token: %w", err)
279 }
280
281 // Print the token details
282 fmt.Println("Header:")
283 if err := printJSON(token.Header); err != nil {
284 return fmt.Errorf("failed to output header: %w", err)
285 }
286
287 fmt.Println("Claims:")
288 if err := printJSON(token.Claims); err != nil {
289 return fmt.Errorf("failed to output claims: %w", err)
290 }
291
292 return nil
293 }
294
295 func isEs() bool {
296 return strings.HasPrefix(*flagAlg, "ES")
297 }
298
299 func isRs() bool {
300 return strings.HasPrefix(*flagAlg, "RS") || strings.HasPrefix(*flagAlg, "PS")
301 }
302
303 func isEd() bool {
304 return *flagAlg == "EdDSA"
305 }
306
307 func isNone() bool {
308 return *flagAlg == "none"
309 }
310
311 func algHelp() string {
312 algs := jwt.GetAlgorithms()
313 sort.Strings(algs)
314
315 var b strings.Builder
316 b.WriteString("signing algorithm identifier, one of\n")
317 for i, alg := range algs {
318 if i > 0 {
319 if i%7 == 0 {
320 b.WriteString(",\n")
321 } else {
322 b.WriteString(", ")
323 }
324 }
325 b.WriteString(alg)
326 }
327 return b.String()
328 }
329
330 type ArgList map[string]string
331
332 func (l ArgList) String() string {
333 data, _ := json.Marshal(l)
334 return string(data)
335 }
336
337 func (l ArgList) Set(arg string) error {
338 parts := strings.SplitN(arg, "=", 2)
339 if len(parts) != 2 {
340 return fmt.Errorf("invalid argument '%v'. Must use format 'key=value'. %v", arg, parts)
341 }
342 l[parts[0]] = parts[1]
343 return nil
344 }