From 0f42df9865544f728945f5816497d69ad2790949 Mon Sep 17 00:00:00 2001 From: "Vojtech Vitek (golang.cz)" Date: Wed, 13 Nov 2024 15:54:23 +0100 Subject: [PATCH] Allow 2 mins as acceptable skew for session JWTs (#24) * Allow 2 mins as acceptable skew for session JWTs * Fix tests --- middleware.go | 4 +++- middleware_test.go | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/middleware.go b/middleware.go index 72a8f4a..c0aabcb 100644 --- a/middleware.go +++ b/middleware.go @@ -5,6 +5,7 @@ import ( "errors" "net/http" "strings" + "time" "github.com/go-chi/jwtauth/v5" "github.com/lestrrat-go/jwx/v2/jwt" @@ -46,7 +47,7 @@ func (o *Options) ApplyDefaults() { func Session(cfg Options) func(next http.Handler) http.Handler { cfg.ApplyDefaults() - auth := jwtauth.New("HS256", []byte(cfg.JWTSecret), nil) + auth := jwtauth.New("HS256", []byte(cfg.JWTSecret), nil, jwt.WithAcceptableSkew(2*time.Minute)) return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -70,6 +71,7 @@ func Session(cfg Options) func(next http.Handler) http.Handler { } } + // Verify JWT token and validate its claims. token, err := jwtauth.VerifyRequest(auth, r, jwtauth.TokenFromHeader) if err != nil { if errors.Is(err, jwtauth.ErrExpired) { diff --git a/middleware_test.go b/middleware_test.go index 0d4af22..ed8f8d7 100644 --- a/middleware_test.go +++ b/middleware_test.go @@ -264,7 +264,7 @@ func TestInvalid(t *testing.T) { assert.ErrorIs(t, err, proto.ErrUnauthorized) // Expired JWT Token - claims["exp"] = time.Now().Add(-time.Second).Unix() + claims["exp"] = time.Now().Add(-5 * time.Minute).Unix() // Note: Session() middleware allows some skew. expiredJWT := authcontrol.S2SToken(JWTSecret, claims) // Expired JWT Token valid method