add jwt custom validate supported

This commit is contained in:
Yavolte 2025-06-18 15:51:11 +08:00
parent 0bc3f9d170
commit 805ad282f5
1 changed files with 16 additions and 2 deletions

View File

@ -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
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)
}