-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwt.go
179 lines (146 loc) · 4.27 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
package medad_jwt_middleware
import (
"context"
"fmt"
"strings"
"net/http"
"encoding/base64"
"crypto/hmac"
"crypto/sha256"
)
type Config struct {
Secret string `json:"secret,omitempty"`
ProxyHeaderName string `json:"proxyHeaderName,omitempty"`
AuthHeader string `json:"authHeader,omitempty"`
HeaderPrefix string `json:"headerPrefix,omitempty"`
SecretKey string `json:"secretKey,omitempty"`
AccessKey string `json:"accessKey,omitempty"`
}
func CreateConfig() *Config {
return &Config{}
}
type JWT struct {
next http.Handler
name string
secret string
proxyHeaderName string
authHeader string
headerPrefix string
secretKey string
accessKey string
}
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 = "injectedPayload"
}
if len(config.AuthHeader) == 0 {
config.AuthHeader = "Authorization"
}
if len(config.HeaderPrefix) == 0 {
config.HeaderPrefix = "Bearer"
}
if len(config.SecretKey) == 0 {
config.SecretKey = "Secret-Key"
}
if len(config.AccessKey) == 0 {
config.AccessKey = "Access-Key"
}
return &JWT{
next: next,
name: name,
secret: config.Secret,
proxyHeaderName: config.ProxyHeaderName,
authHeader: config.AuthHeader,
headerPrefix: config.HeaderPrefix,
secretKey: config.SecretKey,
accessKey: config.AccessKey,
}, nil
}
func (j *JWT) ServeHTTP(res http.ResponseWriter, req *http.Request) {
headerToken := req.Header.Get(j.authHeader)
secretKey := req.Header.Get(j.secretKey)
accessKey := req.Header.Get(j.accessKey)
if len(secretKey) != 0 && len(accessKey) != 0 {
j.next.ServeHTTP(res, req)
return
}
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, "Request error", 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
}