github.com/core-coin/go-core/v2@v2.1.9/node/jwt_handler.go (about) 1 // Copyright 2024 by the Authors 2 // This file is part of the go-core library. 3 // 4 // The go-core library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-core library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-core library. If not, see <http://www.gnu.org/licenses/>. 16 17 package node 18 19 import ( 20 "net/http" 21 "strings" 22 "time" 23 24 "github.com/golang-jwt/jwt/v4" 25 ) 26 27 const jwtExpiryTimeout = 60 * time.Second 28 29 type jwtHandler struct { 30 keyFunc func(token *jwt.Token) (interface{}, error) 31 next http.Handler 32 } 33 34 // newJWTHandler creates a http.Handler with jwt authentication support. 35 func newJWTHandler(secret []byte, next http.Handler) http.Handler { 36 return &jwtHandler{ 37 keyFunc: func(token *jwt.Token) (interface{}, error) { 38 return secret, nil 39 }, 40 next: next, 41 } 42 } 43 44 // ServeHTTP implements http.Handler 45 func (handler *jwtHandler) ServeHTTP(out http.ResponseWriter, r *http.Request) { 46 var ( 47 strToken string 48 claims jwt.RegisteredClaims 49 ) 50 if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "Bearer ") { 51 strToken = strings.TrimPrefix(auth, "Bearer ") 52 } 53 if len(strToken) == 0 { 54 http.Error(out, "missing token", http.StatusForbidden) 55 return 56 } 57 // We explicitly set only HS256 allowed, and also disables the 58 // claim-check: the RegisteredClaims internally requires 'iat' to 59 // be no later than 'now', but we allow for a bit of drift. 60 token, err := jwt.ParseWithClaims(strToken, &claims, handler.keyFunc, 61 jwt.WithValidMethods([]string{"HS256"}), 62 jwt.WithoutClaimsValidation()) 63 64 switch { 65 case err != nil: 66 http.Error(out, err.Error(), http.StatusForbidden) 67 case !token.Valid: 68 http.Error(out, "invalid token", http.StatusForbidden) 69 case !claims.VerifyExpiresAt(time.Now(), false): // optional 70 http.Error(out, "token is expired", http.StatusForbidden) 71 case claims.IssuedAt == nil: 72 http.Error(out, "missing issued-at", http.StatusForbidden) 73 case time.Since(claims.IssuedAt.Time) > jwtExpiryTimeout: 74 http.Error(out, "stale token", http.StatusForbidden) 75 case time.Until(claims.IssuedAt.Time) > jwtExpiryTimeout: 76 http.Error(out, "future token", http.StatusForbidden) 77 default: 78 handler.next.ServeHTTP(out, r) 79 } 80 }