forked from akhettar/gin-jwt-cognito
-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.go
403 lines (329 loc) · 9.3 KB
/
auth.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
399
400
401
402
403
package jwt
import (
"crypto/rsa"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"log"
"math/big"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
jwtgo "github.com/golang-jwt/jwt/v5"
)
var (
// AuthHeaderEmptyError thrown when an empty Authorization header is received
AuthHeaderEmptyError = errors.New("HTTP authorization header empty")
// InvalidAuthHeaderError thrown when an invalid Authorization header is received
InvalidAuthHeaderError = errors.New("invalid HTTP authorization header")
)
const (
// AuthenticateHeader the Gin authenticate header
AuthenticateHeader = "WWW-Authenticate"
// AuthorizationHeader the auth header that gets passed to all services
AuthorizationHeader = "Authorization"
// Forward slash character
ForwardSlash = "/"
// HEADER used by the JWT middle ware
HEADER = "header"
// IssuerFieldName the issuer field name
IssuerFieldName = "iss"
)
// AuthMiddleware middleware
type AuthMiddleware struct {
// User can define own Unauthorized func.
Unauthorized func(*gin.Context, int, string)
Timeout time.Duration
// TokenLookup the header name of the token
TokenLookup string
// TimeFunc
TimeFunc func() time.Time
// Realm name to display to the user. Required.
Realm string
// to verify issuer
VerifyIssuer bool
// Region aws region
Region string
// UserPoolID the cognito user pool id
UserPoolID string
// The issuer
Iss string
// JWK public JSON Web Key (JWK) for your user pool
JWK map[string]JWKKey
// Allowed Client Ids
AllowedClientIds []string
}
// JWK is json data struct for JSON Web Key
type JWK struct {
Keys []JWKKey
}
// JWKKey is json data struct for cognito jwk key
type JWKKey struct {
Alg string
E string
Kid string
Kty string
N string
Use string
}
// AuthError auth error response
type AuthError struct {
Code int `json:"code"`
Message any `json:"message"`
}
// MiddlewareInit initialize jwt configs.
func (mw *AuthMiddleware) MiddlewareInit() {
if mw.TokenLookup == "" {
mw.TokenLookup = "header:" + AuthorizationHeader
}
if mw.Timeout == 0 {
mw.Timeout = time.Hour
}
if mw.TimeFunc == nil {
mw.TimeFunc = time.Now
}
if mw.Unauthorized == nil {
mw.Unauthorized = func(c *gin.Context, code int, message string) {
c.JSON(code, AuthError{Code: code, Message: message})
}
}
if mw.Realm == "" {
mw.Realm = "gin jwt"
}
}
func (mw *AuthMiddleware) middlewareImpl(c *gin.Context) {
// Parse the given token
var tokenStr string
var err error
parts := strings.Split(mw.TokenLookup, ":")
switch parts[0] {
case HEADER:
tokenStr, err = mw.jwtFromHeader(c, parts[1])
}
if err != nil {
log.Printf("jwtFromHeader error: %s", err.Error())
mw.unauthorized(c, http.StatusUnauthorized, err.Error())
return
}
// Info.Printf("tokenStr: %v", tokenStr)
token, err := mw.parse(tokenStr)
if err != nil {
log.Printf("JWT token Parser error: %s", err.Error())
mw.unauthorized(c, http.StatusUnauthorized, err.Error())
return
}
c.Set("JWT_TOKEN", token)
c.Next()
}
func (mw *AuthMiddleware) jwtFromHeader(c *gin.Context, key string) (string, error) {
authHeader := c.Request.Header.Get(key)
if authHeader == "" {
return "", AuthHeaderEmptyError
}
return authHeader, nil
}
func (mw *AuthMiddleware) unauthorized(c *gin.Context, code int, message string) {
if mw.Realm == "" {
mw.Realm = "gin jwt"
}
c.Header(AuthenticateHeader, "JWT realm="+mw.Realm)
c.Abort()
mw.Unauthorized(c, code, message)
return
}
// MiddlewareFunc implements the Middleware interface.
func (mw *AuthMiddleware) MiddlewareFunc() gin.HandlerFunc {
// initialise
mw.MiddlewareInit()
return func(c *gin.Context) {
mw.middlewareImpl(c)
return
}
}
// AuthJWTMiddleware create an instance of the middle ware function
func AuthJWTMiddleware(iss, userPoolID, region string, allowedClientIds []string) (*AuthMiddleware, error) {
// Download the public json web key for the given user pool ID at the start of the plugin
jwk, err := getJWK(fmt.Sprintf("https://cognito-idp.%v.amazonaws.com/%v/.well-known/jwks.json", region, userPoolID))
if err != nil {
return nil, err
}
authMiddleware := &AuthMiddleware{
Timeout: time.Hour,
Unauthorized: func(c *gin.Context, code int, message string) {
c.JSON(code, AuthError{Code: code, Message: message})
},
// Token header
TokenLookup: "header:" + AuthorizationHeader,
TimeFunc: time.Now,
JWK: jwk,
Iss: iss,
Region: region,
UserPoolID: userPoolID,
AllowedClientIds: allowedClientIds,
}
return authMiddleware, nil
}
func (mw *AuthMiddleware) parse(tokenStr string) (*jwtgo.Token, error) {
// 0. remove "Bearer " from the tokenStr
tokenStr = strings.Split(tokenStr, "Bearer ")[1]
// 1. Decode the token string into JWT format.
token, err := jwtgo.Parse(tokenStr, func(token *jwtgo.Token) (interface{}, error) {
// cognito user pool : RS256
if _, ok := token.Method.(*jwtgo.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
// 5. Get the kid from the JWT token header and retrieve the corresponding JSON Web Key that was stored
if kid, ok := token.Header["kid"]; ok {
if kidStr, ok := kid.(string); ok {
key := mw.JWK[kidStr]
// 6. Verify the signature of the decoded JWT token.
rsaPublicKey := convertKey(key.E, key.N)
return rsaPublicKey, nil
}
}
// rsa public key
return "", nil
})
if err != nil {
return token, err
}
claims := token.Claims.(jwtgo.MapClaims)
iss, ok := claims["iss"]
if !ok {
return token, fmt.Errorf("token does not contain issuer")
}
issStr := iss.(string)
if strings.Contains(issStr, "cognito-idp") {
err = validateAWSJwtClaims(claims, mw.Region, mw.UserPoolID, mw.AllowedClientIds)
if err != nil {
return token, err
}
}
if token.Valid {
return token, nil
}
return token, err
}
// validateAWSJwtClaims validates AWS Cognito User Pool JWT
func validateAWSJwtClaims(claims jwtgo.MapClaims, region, userPoolID string, allowedClientIds []string) error {
var err error
// 3. Check the iss claim. It should match your user pool.
issShoudBe := fmt.Sprintf("https://cognito-idp.%v.amazonaws.com/%v", region, userPoolID)
err = validateClaimItem("iss", []string{issShoudBe}, claims)
if err != nil {
Error.Printf("Failed to validate the jwt token claims %v", err)
return err
}
// 4. Check the token_use claim.
validateTokenUse := func() error {
if tokenUse, ok := claims["token_use"]; ok {
if tokenUseStr, ok := tokenUse.(string); ok {
if tokenUseStr == "id" || tokenUseStr == "access" {
return nil
}
}
}
return errors.New("token_use should be id or access")
}
err = validateTokenUse()
if err != nil {
return err
}
// 7. Check the exp claim and make sure the token is not expired.
err = validateExpired(claims)
if err != nil {
return err
}
// 8. Check client id must be in the allowed list
err = validateClientId(claims, allowedClientIds)
if err != nil {
return err
}
return nil
}
func validateClaimItem(key string, keyShouldBe []string, claims jwtgo.MapClaims) error {
if val, ok := claims[key]; ok {
if valStr, ok := val.(string); ok {
for _, shouldbe := range keyShouldBe {
if valStr == shouldbe {
return nil
}
}
}
}
return fmt.Errorf("%v does not match any of valid values: %v", key, keyShouldBe)
}
func validateExpired(claims jwtgo.MapClaims) error {
if tokenExp, ok := claims["exp"]; ok {
if exp, ok := tokenExp.(float64); ok {
now := time.Now().Unix()
// Info.Printf("current unixtime : %v\n", now)
// Info.Printf("expire unixtime : %v\n", int64(exp))
if int64(exp) > now {
return nil
}
}
return errors.New("cannot parse token exp")
}
return errors.New("token is expired")
}
func validateClientId(claims jwtgo.MapClaims, allowedClientIds []string) error {
if tokenClientId, ok := claims["client_id"]; ok {
if clientId, ok := tokenClientId.(string); ok {
// Info.Printf("clientId: %v\n", clientId)
// check if present clientId is in the allowed list
for _, v := range allowedClientIds {
// Info.Printf("v in allowedClientIds: %v\n", v)
if v == clientId {
return nil
}
}
return fmt.Errorf("this clientid %v is not allowed", clientId)
}
return errors.New("cannot parse token clientid")
}
return errors.New("token clientid part is not found")
}
func convertKey(rawE, rawN string) *rsa.PublicKey {
decodedE, err := base64.RawURLEncoding.DecodeString(rawE)
if err != nil {
panic(err)
}
if len(decodedE) < 4 {
ndata := make([]byte, 4)
copy(ndata[4-len(decodedE):], decodedE)
decodedE = ndata
}
pubKey := &rsa.PublicKey{
N: &big.Int{},
E: int(binary.BigEndian.Uint32(decodedE[:])),
}
decodedN, err := base64.RawURLEncoding.DecodeString(rawN)
if err != nil {
panic(err)
}
pubKey.N.SetBytes(decodedN)
return pubKey
}
// Download the json web public key for the given user pool id
func getJWK(jwkURL string) (map[string]JWKKey, error) {
Info.Printf("Downloading the jwk from the given url %s", jwkURL)
jwk := &JWK{}
var myClient = &http.Client{Timeout: 10 * time.Second}
r, err := myClient.Get(jwkURL)
if err != nil {
return nil, err
}
defer r.Body.Close()
if err := json.NewDecoder(r.Body).Decode(jwk); err != nil {
return nil, err
}
jwkMap := make(map[string]JWKKey, 0)
for _, jwk := range jwk.Keys {
jwkMap[jwk.Kid] = jwk
}
return jwkMap, nil
}