jwt_handler.go 2.64 KB
Newer Older
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
// Copyright 2022 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package node

import (
	"net/http"
	"strings"
	"time"

	"github.com/golang-jwt/jwt/v4"
)

27 28
const jwtExpiryTimeout = 60 * time.Second

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
type jwtHandler struct {
	keyFunc func(token *jwt.Token) (interface{}, error)
	next    http.Handler
}

// newJWTHandler creates a http.Handler with jwt authentication support.
func newJWTHandler(secret []byte, next http.Handler) http.Handler {
	return &jwtHandler{
		keyFunc: func(token *jwt.Token) (interface{}, error) {
			return secret, nil
		},
		next: next,
	}
}

// ServeHTTP implements http.Handler
func (handler *jwtHandler) ServeHTTP(out http.ResponseWriter, r *http.Request) {
	var (
		strToken string
		claims   jwt.RegisteredClaims
	)
	if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "Bearer ") {
		strToken = strings.TrimPrefix(auth, "Bearer ")
	}
	if len(strToken) == 0 {
54
		http.Error(out, "missing token", http.StatusUnauthorized)
55 56 57 58 59 60 61 62 63 64 65
		return
	}
	// We explicitly set only HS256 allowed, and also disables the
	// claim-check: the RegisteredClaims internally requires 'iat' to
	// be no later than 'now', but we allow for a bit of drift.
	token, err := jwt.ParseWithClaims(strToken, &claims, handler.keyFunc,
		jwt.WithValidMethods([]string{"HS256"}),
		jwt.WithoutClaimsValidation())

	switch {
	case err != nil:
66
		http.Error(out, err.Error(), http.StatusUnauthorized)
67
	case !token.Valid:
68
		http.Error(out, "invalid token", http.StatusUnauthorized)
69
	case !claims.VerifyExpiresAt(time.Now(), false): // optional
70
		http.Error(out, "token is expired", http.StatusUnauthorized)
71
	case claims.IssuedAt == nil:
72
		http.Error(out, "missing issued-at", http.StatusUnauthorized)
73
	case time.Since(claims.IssuedAt.Time) > jwtExpiryTimeout:
74
		http.Error(out, "stale token", http.StatusUnauthorized)
75
	case time.Until(claims.IssuedAt.Time) > jwtExpiryTimeout:
76
		http.Error(out, "future token", http.StatusUnauthorized)
77 78 79 80
	default:
		handler.next.ServeHTTP(out, r)
	}
}