-
Notifications
You must be signed in to change notification settings - Fork 46
/
jwt.go
398 lines (357 loc) · 11.2 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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package middleware
// github.com/pilinux/gorest
// The MIT License (MIT)
// Copyright (c) 2022 pilinux
import (
"crypto/ecdsa"
"crypto/rsa"
"fmt"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
)
// JWTParameters - params to configure JWT
type JWTParameters struct {
Algorithm string
AccessKey []byte
AccessKeyTTL int
RefreshKey []byte
RefreshKeyTTL int
PrivKeyECDSA *ecdsa.PrivateKey
PubKeyECDSA *ecdsa.PublicKey
PrivKeyRSA *rsa.PrivateKey
PubKeyRSA *rsa.PublicKey
Audience string
Issuer string
AccNbf int
RefNbf int
Subject string
}
// JWTParams - exported variables
var JWTParams JWTParameters
// MyCustomClaims ...
type MyCustomClaims struct {
AuthID uint64 `json:"authID,omitempty"`
Email string `json:"email,omitempty"`
Role string `json:"role,omitempty"`
Scope string `json:"scope,omitempty"`
TwoFA string `json:"twoFA,omitempty"`
SiteLan string `json:"siteLan,omitempty"`
Custom1 string `json:"custom1,omitempty"`
Custom2 string `json:"custom2,omitempty"`
}
// JWTClaims ...
type JWTClaims struct {
MyCustomClaims
jwt.RegisteredClaims
}
// JWTPayload ...
type JWTPayload struct {
AccessJWT string `json:"accessJWT,omitempty"`
RefreshJWT string `json:"refreshJWT,omitempty"`
TwoAuth string `json:"twoFA,omitempty"`
RecoveryKey string `json:"recoveryKey,omitempty"`
}
// JWT - validate access token
func JWT() gin.HandlerFunc {
return func(c *gin.Context) {
var jwtPayload JWTPayload
var token *jwt.Token
var val string
var vals []string
// first try to read the cookie
accessJWT, err := c.Cookie("accessJWT")
// accessJWT is available in the cookie
if err == nil {
jwtPayload.AccessJWT = accessJWT
goto VerifyClaims
}
// accessJWT is not available in the cookie
// try to read the Authorization header
val = c.Request.Header.Get("Authorization")
if len(val) == 0 || !strings.Contains(val, "Bearer") {
// no vals or no bearer found
c.AbortWithStatusJSON(http.StatusUnauthorized, "token missing")
return
}
vals = strings.Split(val, " ")
// Authorization: Bearer {access} => length is 2
// Authorization: Bearer {access} {refresh} => length is 3
if len(vals) < 2 {
c.AbortWithStatusJSON(http.StatusUnauthorized, "token missing")
return
}
jwtPayload.AccessJWT = vals[1]
VerifyClaims:
token, err = jwt.ParseWithClaims(jwtPayload.AccessJWT, &JWTClaims{}, ValidateAccessJWT)
if err != nil {
// error parsing JWT
c.AbortWithStatusJSON(http.StatusUnauthorized, err.Error())
return
}
if claims, ok := token.Claims.(*JWTClaims); ok && token.Valid {
c.Set("authID", claims.AuthID)
c.Set("email", claims.Email)
c.Set("role", claims.Role)
c.Set("scope", claims.Scope)
c.Set("tfa", claims.TwoFA)
c.Set("siteLan", claims.SiteLan)
c.Set("custom1", claims.Custom1)
c.Set("custom2", claims.Custom2)
c.Set("expAccess", claims.ExpiresAt.Unix()) // in UTC
c.Set("iatAccess", claims.IssuedAt.Unix()) // in UTC
c.Set("jtiAccess", claims.ID)
}
c.Next()
}
}
// RefreshJWT - validate refresh token
func RefreshJWT() gin.HandlerFunc {
return func(c *gin.Context) {
var jwtPayload JWTPayload
var val string
var vals []string
// first try to read the cookie
refreshJWT, err := c.Cookie("refreshJWT")
// refreshJWT is available in the cookie
if err == nil {
jwtPayload.RefreshJWT = refreshJWT
goto VerifyClaims
}
// refreshJWT is not available in the cookie
// try to read the Authorization header
val = c.Request.Header.Get("Authorization")
if len(val) == 0 || !strings.Contains(val, "Bearer") {
// no vals or no bearer found
goto CheckReqBody
}
vals = strings.Split(val, " ")
// Authorization: Bearer {refresh} => length is 2
// Authorization: Bearer {access} {refresh} => length is 3
if len(vals) < 2 {
c.AbortWithStatusJSON(http.StatusUnauthorized, "token missing")
return
}
jwtPayload.RefreshJWT = vals[1]
if len(vals) == 3 {
jwtPayload.RefreshJWT = vals[2]
}
goto VerifyClaims
CheckReqBody:
// refreshJWT is not available in the cookie or Authorization header
// try to read the request body
if err := c.ShouldBindJSON(&jwtPayload); err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, err.Error())
return
}
jwtPayload.RefreshJWT = strings.TrimSpace(jwtPayload.RefreshJWT)
VerifyClaims:
token, err := jwt.ParseWithClaims(jwtPayload.RefreshJWT, &JWTClaims{}, ValidateRefreshJWT)
if err != nil {
// error parsing JWT
c.AbortWithStatusJSON(http.StatusUnauthorized, err.Error())
return
}
if claims, ok := token.Claims.(*JWTClaims); ok && token.Valid {
c.Set("authID", claims.AuthID)
c.Set("email", claims.Email)
c.Set("role", claims.Role)
c.Set("scope", claims.Scope)
c.Set("tfa", claims.TwoFA)
c.Set("siteLan", claims.SiteLan)
c.Set("custom1", claims.Custom1)
c.Set("custom2", claims.Custom2)
c.Set("expRefresh", claims.ExpiresAt.Unix()) // in UTC
c.Set("iatRefresh", claims.IssuedAt.Unix()) // in UTC
c.Set("jtiRefresh", claims.ID)
}
c.Next()
}
}
// ValidateHMACAccess - validate hash based access token
func ValidateHMACAccess(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return JWTParams.AccessKey, nil
}
// ValidateHMACRefresh - validate hash based refresh token
func ValidateHMACRefresh(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return JWTParams.RefreshKey, nil
}
// ValidateECDSA - validate elliptic curve digital signature algorithm based token
func ValidateECDSA(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return JWTParams.PubKeyECDSA, nil
}
// ValidateRSA - validate Rivest–Shamir–Adleman cryptosystem based token
func ValidateRSA(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return JWTParams.PubKeyRSA, nil
}
// ValidateAccessJWT - verify the access JWT's signature, and validate its claims
func ValidateAccessJWT(token *jwt.Token) (interface{}, error) {
alg := JWTParams.Algorithm
switch alg {
case "HS256", "HS384", "HS512":
return ValidateHMACAccess(token)
case "ES256", "ES384", "ES512":
return ValidateECDSA(token)
case "RS256", "RS384", "RS512":
return ValidateRSA(token)
default:
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
}
// ValidateRefreshJWT - verify the refresh JWT's signature, and validate its claims
func ValidateRefreshJWT(token *jwt.Token) (interface{}, error) {
alg := JWTParams.Algorithm
switch alg {
case "HS256", "HS384", "HS512":
return ValidateHMACRefresh(token)
case "ES256", "ES384", "ES512":
return ValidateECDSA(token)
case "RS256", "RS384", "RS512":
return ValidateRSA(token)
default:
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
}
// GetJWT - issue new tokens
func GetJWT(customClaims MyCustomClaims, tokenType string) (string, string, error) {
var (
key []byte
privKeyECDSA *ecdsa.PrivateKey
privKeyRSA *rsa.PrivateKey
ttl int
nbf int
)
if tokenType == "access" {
key = JWTParams.AccessKey
ttl = JWTParams.AccessKeyTTL
nbf = JWTParams.AccNbf
}
if tokenType == "refresh" {
key = JWTParams.RefreshKey
ttl = JWTParams.RefreshKeyTTL
nbf = JWTParams.RefNbf
}
// Create the Claims
claims := JWTClaims{
MyCustomClaims{
AuthID: customClaims.AuthID,
Email: customClaims.Email,
Role: customClaims.Role,
Scope: customClaims.Scope,
TwoFA: customClaims.TwoFA,
SiteLan: customClaims.SiteLan,
Custom1: customClaims.Custom1,
Custom2: customClaims.Custom2,
},
jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Minute * time.Duration(ttl))),
ID: uuid.NewString(),
IssuedAt: jwt.NewNumericDate(time.Now()),
Issuer: JWTParams.Issuer,
Subject: JWTParams.Subject,
},
}
if JWTParams.Audience != "" {
claims.Audience = []string{JWTParams.Audience}
}
if nbf > 0 {
claims.NotBefore = jwt.NewNumericDate(time.Now().Add(time.Second * time.Duration(nbf)))
}
var token *jwt.Token
alg := JWTParams.Algorithm
switch alg {
case "HS256":
token = jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
case "HS384":
token = jwt.NewWithClaims(jwt.SigningMethodHS384, claims)
case "HS512":
token = jwt.NewWithClaims(jwt.SigningMethodHS512, claims)
case "ES256":
privKeyECDSA = JWTParams.PrivKeyECDSA
token = jwt.NewWithClaims(jwt.SigningMethodES256, claims)
case "ES384":
privKeyECDSA = JWTParams.PrivKeyECDSA
token = jwt.NewWithClaims(jwt.SigningMethodES384, claims)
case "ES512":
privKeyECDSA = JWTParams.PrivKeyECDSA
token = jwt.NewWithClaims(jwt.SigningMethodES512, claims)
case "RS256":
privKeyRSA = JWTParams.PrivKeyRSA
token = jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
case "RS384":
privKeyRSA = JWTParams.PrivKeyRSA
token = jwt.NewWithClaims(jwt.SigningMethodRS384, claims)
case "RS512":
privKeyRSA = JWTParams.PrivKeyRSA
token = jwt.NewWithClaims(jwt.SigningMethodRS512, claims)
default:
token = jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
}
var jwtValue string
var err error
// HMAC
if alg == "HS256" || alg == "HS384" || alg == "HS512" {
jwtValue, err = token.SignedString(key)
if err != nil {
return "", "", err
}
}
// ECDSA
//
// ES256
// prime256v1: X9.62/SECG curve over a 256 bit prime field, also known as P-256 or NIST P-256
// widely used, recommended for general-purpose cryptographic operations
// openssl ecparam -name prime256v1 -genkey -noout -out private-key.pem
// openssl ec -in private-key.pem -pubout -out public-key.pem
//
// ES384
// secp384r1: NIST/SECG curve over a 384 bit prime field
// openssl ecparam -name secp384r1 -genkey -noout -out private-key.pem
// openssl ec -in private-key.pem -pubout -out public-key.pem
//
// ES512
// secp521r1: NIST/SECG curve over a 521 bit prime field
// openssl ecparam -name secp521r1 -genkey -noout -out private-key.pem
// openssl ec -in private-key.pem -pubout -out public-key.pem
if alg == "ES256" || alg == "ES384" || alg == "ES512" {
jwtValue, err = token.SignedString(privKeyECDSA)
if err != nil {
return "", "", err
}
}
// RSA
//
// RS256
// openssl genpkey -algorithm RSA -out private-key.pem -pkeyopt rsa_keygen_bits:2048
// openssl rsa -in private-key.pem -pubout -out public-key.pem
//
// RS384
// openssl genpkey -algorithm RSA -out private-key.pem -pkeyopt rsa_keygen_bits:3072
// openssl rsa -in private-key.pem -pubout -out public-key.pem
//
// RS512
// openssl genpkey -algorithm RSA -out private-key.pem -pkeyopt rsa_keygen_bits:4096
// openssl rsa -in private-key.pem -pubout -out public-key.pem
if alg == "RS256" || alg == "RS384" || alg == "RS512" {
jwtValue, err = token.SignedString(privKeyRSA)
if err != nil {
return "", "", err
}
}
return jwtValue, claims.ID, nil
}