优化jwt token解析方法

This commit is contained in:
白茶清欢 2023-02-12 00:36:24 +08:00
parent 661eed5f0a
commit 1a6a3e1d31

16
jwt.go
View File

@ -46,7 +46,10 @@ func (j *ownJwt) Generate(signMethod jwt.SigningMethod, secret string, claims jw
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 20:13 2023/2/11 // Date : 20:13 2023/2/11
func (j *ownJwt) Validate(inputToken string, secret string) (jwt.Claims, error) { func (j *ownJwt) Validate(inputToken string, secret string, convert func(c jwt.Claims) error) error {
if nil == convert {
return errors.New("convert func is nil")
}
var ( var (
token *jwt.Token token *jwt.Token
err error err error
@ -55,10 +58,15 @@ func (j *ownJwt) Validate(inputToken string, secret string) (jwt.Claims, error)
if token, err = jwt.Parse(inputToken, func(tokenInfo *jwt.Token) (interface{}, error) { if token, err = jwt.Parse(inputToken, func(tokenInfo *jwt.Token) (interface{}, error) {
return []byte(secret), nil return []byte(secret), nil
}); nil != err { }); nil != err {
return nil, errors.New("token parse fail : " + err.Error()) return errors.New("token parse fail : " + err.Error())
} }
if !token.Valid { if !token.Valid {
return nil, errors.New("token is valid : " + err.Error()) return errors.New("token is valid : " + err.Error())
} }
return token.Claims, nil if nil != convert {
if err = convert(token.Claims); nil != err {
return err
}
}
return nil
} }