-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwt.go
192 lines (158 loc) · 4.68 KB
/
jwt.go
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package jwt_token
import (
"context"
"fmt"
"net/http"
"strings"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"strconv"
"time"
)
type Config struct {
Secret string `json:"secret,omitempty"`
ProxyHeaderName string `json:"proxyHeaderName,omitempty"`
AuthHeader string `json:"authHeader,omitempty"`
HeaderPrefix string `json:"headerPrefix,omitempty"`
ExpireMode string `json:"expireMode,omitempty"`
IgnoreOptions bool `json:"ignoreOptions,omitempty"`
}
func CreateConfig() *Config {
return &Config{
IgnoreOptions: true, // Default value set here
}
}
type JWT struct {
next http.Handler
name string
secret string
proxyHeaderName string
authHeader string
headerPrefix string
expireMode string
ignoreOptions bool
}
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
if len(config.Secret) == 0 {
config.Secret = "SECRET"
}
if len(config.ProxyHeaderName) == 0 {
config.ProxyHeaderName = "ipayload"
}
if len(config.AuthHeader) == 0 {
config.AuthHeader = "Authorization"
}
if len(config.HeaderPrefix) == 0 {
config.HeaderPrefix = "Bearer"
}
if len(config.ExpireMode) == 0 {
config.ExpireMode = "none"
}
return &JWT{
next: next,
name: name,
secret: config.Secret,
proxyHeaderName: config.ProxyHeaderName,
authHeader: config.AuthHeader,
headerPrefix: config.HeaderPrefix,
expireMode: config.ExpireMode,
ignoreOptions: config.IgnoreOptions, // Assign the config value (allowing override)
}, nil
}
func (j *JWT) ServeHTTP(res http.ResponseWriter, req *http.Request) {
if j.ignoreOptions && req.Method == http.MethodOptions {
j.next.ServeHTTP(res, req)
return
}
headerToken := req.Header.Get(j.authHeader)
if len(headerToken) == 0 {
http.Error(res, "Request error", http.StatusUnauthorized)
return
}
token, preprocessError := preprocessJWT(headerToken, j.headerPrefix)
if preprocessError != nil {
http.Error(res, "Request error", http.StatusBadRequest)
return
}
verified, verificationError := verifyJWT(token, j.secret)
if verificationError != nil {
http.Error(res, "Not allowed", http.StatusUnauthorized)
return
}
if verified {
// If true decode payload
payload, decodeErr := decodeBase64(token.payload)
if decodeErr != nil {
http.Error(res, "payload invalid", http.StatusBadRequest)
return
}
if j.expireMode == "header" {
expireS, decodeErr := decodeBase64(token.header)
timestampInt, err := strconv.Atoi(expireS)
if decodeErr != nil || err != nil {
http.Error(res, "header error", http.StatusBadRequest)
return
}
// Compare timestamps
if int(time.Now().Unix()) > timestampInt {
http.Error(res, "expired", http.StatusBadRequest)
return
}
}
// TODO Check for outside of ASCII range characters
// Inject header as proxypayload or configured name
req.Header.Add(j.proxyHeaderName, payload)
fmt.Println(req.Header)
j.next.ServeHTTP(res, req)
} else {
http.Error(res, "Not allowed", http.StatusUnauthorized)
}
}
// Token Deconstructed header token
type Token struct {
header string
payload string
verification string
}
// verifyJWT Verifies jwt token with secret
func verifyJWT(token Token, secret string) (bool, error) {
mac := hmac.New(sha256.New, []byte(secret))
message := token.header + "." + token.payload
mac.Write([]byte(message))
expectedMAC := mac.Sum(nil)
decodedVerification, errDecode := base64.RawURLEncoding.DecodeString(token.verification)
if errDecode != nil {
return false, errDecode
}
if hmac.Equal(decodedVerification, expectedMAC) {
return true, nil
}
return false, nil
// TODO Add time check to jwt verification
}
// preprocessJWT Takes the request header string, strips prefix and whitespaces and returns a Token
func preprocessJWT(reqHeader string, prefix string) (Token, error) {
// fmt.Println("==> [processHeader] SplitAfter")
// structuredHeader := strings.SplitAfter(reqHeader, "Bearer ")[1]
cleanedString := strings.TrimPrefix(reqHeader, prefix)
cleanedString = strings.TrimSpace(cleanedString)
// fmt.Println("<== [processHeader] SplitAfter", cleanedString)
var token Token
tokenSplit := strings.Split(cleanedString, ".")
if len(tokenSplit) != 3 {
return token, fmt.Errorf("Invalid token")
}
token.header = tokenSplit[0]
token.payload = tokenSplit[1]
token.verification = tokenSplit[2]
return token, nil
}
// decodeBase64 Decode base64 to string
func decodeBase64(baseString string) (string, error) {
byte, decodeErr := base64.RawURLEncoding.DecodeString(baseString)
if decodeErr != nil {
return baseString, fmt.Errorf("Error decoding")
}
return string(byte), nil
}