Skip to content

Commit b368a1c

Browse files
committed
Add command to print JWT token for customer support
Signed-off-by: Alex Ellis (OpenFaaS Ltd) <alexellis2@gmail.com>
1 parent 6de492c commit b368a1c

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed

commands/print_token.go

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// Copyright (c) Alex Ellis 2017. All rights reserved.
2+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3+
4+
package commands
5+
6+
import (
7+
"encoding/base64"
8+
"encoding/json"
9+
"fmt"
10+
"os"
11+
"strings"
12+
13+
"github.com/spf13/cobra"
14+
)
15+
16+
func init() {
17+
faasCmd.AddCommand(printToken)
18+
}
19+
20+
var printToken = &cobra.Command{
21+
Use: `print-token ./token.txt`,
22+
Short: "Pretty-print the contents of a JWT token",
23+
Example: ` # Print the contents of a JWT token
24+
faas-cli print-token ./token.txt
25+
`,
26+
RunE: runPrintTokenE,
27+
Hidden: true,
28+
}
29+
30+
func runPrintTokenE(cmd *cobra.Command, args []string) error {
31+
32+
if len(args) < 1 {
33+
return fmt.Errorf("provide the filename as an argument i.e. faas-cli print-token ./token.txt")
34+
}
35+
36+
tokenFile := args[0]
37+
38+
data, err := os.ReadFile(tokenFile)
39+
if err != nil {
40+
return err
41+
}
42+
43+
token := string(data)
44+
45+
jwtToken, err := unmarshalJwt(token)
46+
if err != nil {
47+
return err
48+
}
49+
50+
j, err := json.MarshalIndent(jwtToken, "", " ")
51+
if err != nil {
52+
return err
53+
}
54+
55+
fmt.Println(string(j))
56+
57+
return nil
58+
}
59+
60+
type JwtToken struct {
61+
Header map[string]interface{} `json:"header"`
62+
Payload map[string]interface{} `json:"payload"`
63+
}
64+
65+
func unmarshalJwt(token string) (JwtToken, error) {
66+
67+
parts := strings.Split(token, ".")
68+
if len(parts) != 3 {
69+
return JwtToken{}, fmt.Errorf("token should have 3 parts, got %d", len(parts))
70+
}
71+
72+
header, err := base64.RawURLEncoding.DecodeString(parts[0])
73+
if err != nil {
74+
return JwtToken{}, err
75+
}
76+
77+
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
78+
if err != nil {
79+
return JwtToken{}, err
80+
}
81+
82+
var jwt JwtToken
83+
84+
err = json.Unmarshal(header, &jwt.Header)
85+
if err != nil {
86+
return JwtToken{}, err
87+
}
88+
89+
err = json.Unmarshal(payload, &jwt.Payload)
90+
if err != nil {
91+
return JwtToken{}, err
92+
}
93+
94+
return jwt, nil
95+
}

0 commit comments

Comments
 (0)