From 805ad282f56fb7493b4d32cbc6cba1b2b19370de Mon Sep 17 00:00:00 2001 From: Yavolte Date: Wed, 18 Jun 2025 15:51:11 +0800 Subject: [PATCH] add jwt custom validate supported --- middleware/auth/jwt.go | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/middleware/auth/jwt.go b/middleware/auth/jwt.go index 5a4ff40..328ced4 100644 --- a/middleware/auth/jwt.go +++ b/middleware/auth/jwt.go @@ -30,10 +30,13 @@ const ( type Option func(*options) +type ValidateFunc func(ctx context.Context, token string) error + // Parser is a jwt parser type options struct { - allows []string - claims reflect.Type + allows []string + claims reflect.Type + validateFunc ValidateFunc } // WithAllow with allow path @@ -52,6 +55,12 @@ func WithClaims(claims reflect.Type) Option { } } +func WithValidateFunc(fn ValidateFunc) Option { + return func(o *options) { + o.validateFunc = fn + } +} + // isAllowed check if the path is allowed func isAllowed(uripath string, allows []string) bool { for _, str := range allows { @@ -92,6 +101,11 @@ func JWT(keyFunc jwt.Keyfunc, cbs ...Option) middleware.Middleware { if !ok { return errors.ErrAccessDenied } + if opts.validateFunc != nil { + if err = opts.validateFunc(ctx, token); err != nil { + return err + } + } if strings.HasPrefix(token, bearerWord) { token = strings.TrimPrefix(token, bearerWord) }