-
Notifications
You must be signed in to change notification settings - Fork 4
/
jwt.go
366 lines (330 loc) · 12.3 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package main
import (
"encoding/json"
"fmt"
"github.com/go-jose/go-jose/v3"
"github.com/go-jose/go-jose/v3/jwt"
log "github.com/sirupsen/logrus"
"net/http"
"strings"
"time"
)
func jwtAuthAdmin(next func(w http.ResponseWriter, r *http.Request, email string), emails []string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
claims, err := jwtAuth0(r)
if claims != nil && err != nil {
writeErr(w, http.StatusUnauthorized, "invalid_client", "refused", "Token expired: %v, available: %v", claims.Subject, emails)
return
} else if claims == nil && err != nil {
writeErr(w, http.StatusBadRequest, "invalid_request", "blocked", "jwtAuthAdmin error: %v", err)
return
}
for _, email := range emails {
if claims.Subject == email {
log.Printf("Authenticated admin %s\n", email)
next(w, r, email)
return
}
}
writeErr(w, http.StatusBadRequest, "invalid_request", "blocked", "ERR-01,jwtAuthAdmin error: %v != %v", claims.Subject, emails)
}
}
func jwtAuth(next func(w http.ResponseWriter, r *http.Request, claims *TokenClaims)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
claims, err := jwtAuth0(r)
if err != nil {
keys := r.URL.Query()
ru := keys.Get("redirect_uri")
if claims != nil {
if ru != "" {
log.Printf("Token expired: %v", claims.Subject)
w.Header().Set("Location", ru)
w.WriteHeader(http.StatusSeeOther)
} else {
writeErr(w, http.StatusUnauthorized, "invalid_client", "refused", "Token expired: %v", claims.Subject)
}
} else if claims == nil {
if ru != "" {
log.Printf("jwtAuthAdmin error: %v", err)
w.Header().Set("Location", ru)
w.WriteHeader(http.StatusSeeOther)
} else {
writeErr(w, http.StatusBadRequest, "invalid_request", "blocked", "jwtAuthAdmin error: %v", err)
}
}
return
}
next(w, r, claims)
}
}
func jwtAuth0(r *http.Request) (*TokenClaims, error) {
authHeader := r.Header.Get("Authorization")
split := strings.Split(authHeader, " ")
if len(split) != 2 {
return nil, fmt.Errorf("ERR-02, could not split token, auth header is: [%v]", authHeader)
}
bearerToken := split[1]
tok, err := jwt.ParseSigned(bearerToken)
if err != nil {
return nil, fmt.Errorf("ERR-03, could not parse token: %v", bearerToken[1])
}
claims := &TokenClaims{}
if tok.Headers[0].Algorithm == string(jose.RS256) {
err = tok.Claims(privRSA.Public(), claims)
} else if tok.Headers[0].Algorithm == string(jose.HS256) {
err = tok.Claims(jwtKey, claims)
} else if tok.Headers[0].Algorithm == string(jose.EdDSA) {
err = tok.Claims(privEdDSA.Public(), claims)
} else {
return nil, fmt.Errorf("ERR-04, unknown algorithm: %v", tok.Headers[0].Algorithm)
}
if err != nil {
return nil, fmt.Errorf("ERR-05, could not parse claims: %v", bearerToken)
}
if claims.Expiry != nil && !claims.Expiry.Time().After(timeNow()) {
return claims, fmt.Errorf("ERR-06, unauthorized: %v", bearerToken)
}
if claims.Subject == "" {
return nil, fmt.Errorf("ERR-07, no subject: %v", claims)
}
return claims, nil
}
func checkRefreshToken(token string) (*RefreshClaims, error) {
tok, err := jwt.ParseSigned(token)
if err != nil {
return nil, fmt.Errorf("ERR-check-refresh-01, could not check sig %v", err)
}
refreshClaims := &RefreshClaims{}
if tok.Headers[0].Algorithm == string(jose.RS256) {
err := tok.Claims(privRSA.Public(), refreshClaims)
if err != nil {
return nil, fmt.Errorf("ERR-check-refresh-02, could not parse claims %v", err)
}
} else if tok.Headers[0].Algorithm == string(jose.HS256) {
err := tok.Claims(jwtKey, refreshClaims)
if err != nil {
return nil, fmt.Errorf("ERR-check-refresh-03, could not parse claims %v", err)
}
} else if tok.Headers[0].Algorithm == string(jose.EdDSA) {
err := tok.Claims(privEdDSA.Public(), refreshClaims)
if err != nil {
return nil, fmt.Errorf("ERR-check-refresh-04, could not parse claims %v", err)
}
} else {
return nil, fmt.Errorf("ERR-check-refresh-05, could not parse claims, no algo found %v", tok.Headers[0].Algorithm)
}
t := time.Unix(refreshClaims.ExpiresAt, 0)
if !t.After(timeNow()) {
return nil, fmt.Errorf("ERR-check-refresh-06, expired %v", err)
}
return refreshClaims, nil
}
func encodeAccessToken(subject string, scope string, audience string, issuer string, systemMeta map[string]interface{}) (string, error) {
//if we have a system user, the system user only gets an access token that lives as long as the refresh token
//normal users get both, access and refresh token
var expiry *jwt.NumericDate
if subject == "system" {
expiry = jwt.NewNumericDate(timeNow().Add(refreshExp))
} else {
expiry = jwt.NewNumericDate(timeNow().Add(tokenExp))
}
tokenClaims := &TokenClaims{
Scope: scope,
Claims: jwt.Claims{
Expiry: expiry,
Subject: subject,
Audience: []string{audience},
Issuer: issuer,
IssuedAt: jwt.NewNumericDate(timeNow()),
},
}
var sig jose.Signer
var err error
if jwtKey != nil {
sig, err = jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: jwtKey}, (&jose.SignerOptions{}).WithType("JWT"))
} else if privRSA != nil {
sig, err = jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: privRSA}, (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", privRSAKid))
} else if privEdDSA != nil {
sig, err = jose.NewSigner(jose.SigningKey{Algorithm: jose.EdDSA, Key: *privEdDSA}, (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", privEdDSAKid))
} else {
return "", fmt.Errorf("JWT access token %v no key", tokenClaims.Subject)
}
if err != nil {
return "", fmt.Errorf("JWT access token %v failed: %v", tokenClaims.Subject, err)
}
accessTokenString, err := jwt.Signed(sig).Claims(systemMeta).Claims(tokenClaims).CompactSerialize()
if err != nil {
return "", fmt.Errorf("JWT access token %v failed: %v", tokenClaims.Subject, err)
}
if opts.Dev != "" {
log.Printf("Access token: [%s]", accessTokenString)
}
return accessTokenString, nil
}
func encodeCodeToken(subject string, codeChallenge string, codeChallengeMethod string) (string, int64, error) {
cc := &CodeClaims{}
cc.Subject = subject
cc.ExpiresAt = timeNow().Add(codeExp).Unix()
cc.CodeChallenge = codeChallenge
cc.CodeCodeChallengeMethod = codeChallengeMethod
var sig jose.Signer
var err error
if jwtKey != nil {
sig, err = jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: jwtKey}, (&jose.SignerOptions{}).WithType("JWT"))
} else if privRSA != nil {
sig, err = jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: privRSA}, (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", privRSAKid))
} else if privEdDSA != nil {
sig, err = jose.NewSigner(jose.SigningKey{Algorithm: jose.EdDSA, Key: *privEdDSA}, (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", privEdDSAKid))
} else {
return "", 0, fmt.Errorf("JWT refresh token %v no key", subject)
}
if err != nil {
return "", 0, fmt.Errorf("JWT refresh token %v failed: %v", subject, err)
}
codeToken, err := jwt.Signed(sig).Claims(cc).CompactSerialize()
if err != nil {
return "", 0, fmt.Errorf("JWT refresh token %v failed: %v", subject, err)
}
if opts.Dev != "" {
log.Printf("Code token: [%s]", codeToken)
}
return codeToken, cc.ExpiresAt, nil
}
/*
If the option ResetRefresh is set, then every time this function is called, which is
before the createRefreshToken, then the refresh token is renewed and the old one is
not valid anymore.
This function is also used in case of revoking a token, where a new token is created,
but not returned to the user, so the user has to login to get the refresh token
*/
func resetRefreshToken(oldToken string) (string, error) {
newToken, err := genToken()
if err != nil {
return "", err
}
err = updateRefreshToken(oldToken, newToken)
if err != nil {
return "", err
}
return newToken, nil
}
func checkRefresh(email string, token string) (string, string, int64, error) {
result, err := findAuthByEmail(email)
if err != nil {
return "", "", 0, fmt.Errorf("ERR-refresh-03, DB select, %v err %v", email, err)
}
if result.emailToken != nil {
return "", "", 0, fmt.Errorf("ERR-refresh-04, user %v no email verified: %v", email, err)
}
if result.refreshToken == "" || token != result.refreshToken {
if opts.Dev != "" {
log.Printf("refresh token mismatch %v != %v", token, result.refreshToken)
}
return "", "", 0, fmt.Errorf("ERR-refresh-05, refresh token mismatch")
}
return encodeTokens(result)
}
func encodeTokens(result *dbRes) (string, string, int64, error) {
encodedAccessToken, err := encodeAccessTokens(result.email, result.metaSystem)
if err != nil {
return "", "", 0, err
}
encodedRefreshToken, expireAt, err := encodeRefreshTokens(result.email, result.refreshToken)
if err != nil {
return "", "", 0, err
}
return encodedAccessToken, encodedRefreshToken, expireAt, nil
}
func encodeAccessTokens(email string, metaSystem *string) (string, error) {
jsonMapSystem, err := toJsonMap(metaSystem)
if err != nil {
return "", fmt.Errorf("cannot encode system meta in encodeTokens for %v, %v", email, err)
}
encodedAccessToken, err := encodeAccessToken(email, opts.Scope, opts.Audience, opts.Issuer, jsonMapSystem)
if err != nil {
return "", fmt.Errorf("ERR-refresh-06, cannot set access token for %v, %v", email, err)
}
return encodedAccessToken, nil
}
func encodeRefreshTokens(email string, refreshToken string) (string, int64, error) {
if opts.ResetRefresh {
var err error
refreshToken, err = resetRefreshToken(refreshToken)
if err != nil {
return "", 0, fmt.Errorf("ERR-refresh-07, cannot reset access token for %v, %v", email, err)
}
}
encodedRefreshToken, expiresAt, err := encodeRefreshToken(email, refreshToken)
if err != nil {
return "", 0, fmt.Errorf("ERR-refresh-08, cannot set refresh token for %v, %v", email, err)
}
return encodedRefreshToken, expiresAt, nil
}
func checkCodeToken(token string) (*CodeClaims, error) {
tok, err := jwt.ParseSigned(token)
if err != nil {
return nil, fmt.Errorf("ERR-check-refresh-01, could not check sig %v", err)
}
codeClaims := &CodeClaims{}
if tok.Headers[0].Algorithm == string(jose.RS256) {
err := tok.Claims(privRSA.Public(), codeClaims)
if err != nil {
return nil, fmt.Errorf("ERR-check-refresh-02, could not parse claims %v", err)
}
} else if tok.Headers[0].Algorithm == string(jose.HS256) {
err := tok.Claims(jwtKey, codeClaims)
if err != nil {
return nil, fmt.Errorf("ERR-check-refresh-03, could not parse claims %v", err)
}
} else if tok.Headers[0].Algorithm == string(jose.EdDSA) {
err := tok.Claims(privEdDSA.Public(), codeClaims)
if err != nil {
return nil, fmt.Errorf("ERR-check-refresh-04, could not parse claims %v", err)
}
} else {
return nil, fmt.Errorf("ERR-check-refresh-05, could not parse claims, no algo found %v", tok.Headers[0].Algorithm)
}
t := time.Unix(codeClaims.ExpiresAt, 0)
if !t.After(timeNow()) {
return nil, fmt.Errorf("ERR-check-refresh-06, expired %v", err)
}
return codeClaims, nil
}
func encodeRefreshToken(subject string, token string) (string, int64, error) {
rc := &RefreshClaims{}
rc.Subject = subject
rc.ExpiresAt = timeNow().Add(refreshExp).Unix()
rc.Token = token
var sig jose.Signer
var err error
if jwtKey != nil {
sig, err = jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: jwtKey}, (&jose.SignerOptions{}).WithType("JWT"))
} else if privRSA != nil {
sig, err = jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: privRSA}, (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", privRSAKid))
} else if privEdDSA != nil {
sig, err = jose.NewSigner(jose.SigningKey{Algorithm: jose.EdDSA, Key: *privEdDSA}, (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", privEdDSAKid))
} else {
return "", 0, fmt.Errorf("JWT refresh token %v no key", subject)
}
if err != nil {
return "", 0, fmt.Errorf("JWT refresh token %v failed: %v", subject, err)
}
refreshToken, err := jwt.Signed(sig).Claims(rc).CompactSerialize()
if err != nil {
return "", 0, fmt.Errorf("JWT refresh token %v failed: %v", subject, err)
}
if opts.Dev != "" {
log.Printf("Refresh token: [%s]", refreshToken)
}
return refreshToken, rc.ExpiresAt, nil
}
func toJsonMap(jsonStr *string) (map[string]interface{}, error) {
jsonMap := make(map[string]interface{})
if jsonStr != nil {
err := json.Unmarshal([]byte(*jsonStr), &jsonMap)
if err != nil {
return nil, fmt.Errorf("ERR-refresh-06, cannot create json map %v", err)
}
}
return jsonMap, nil
}