2023-02-11 21:14:57 +08:00
|
|
|
// Package util ...
|
|
|
|
//
|
|
|
|
// Description : go-jwt具体实现
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 2023-02-11 20:09
|
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
|
|
|
|
"github.com/dgrijalva/jwt-go"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ownJwt struct {
|
|
|
|
}
|
|
|
|
|
|
|
|
type MyClaims struct {
|
|
|
|
jwt.StandardClaims
|
|
|
|
}
|
|
|
|
|
|
|
|
// Generate 生成 token
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 20:13 2023/2/11
|
|
|
|
func (j *ownJwt) Generate(signMethod jwt.SigningMethod, secret string, claims jwt.Claims) (string, error) {
|
|
|
|
if nil == signMethod {
|
|
|
|
signMethod = jwt.SigningMethodHS256
|
|
|
|
}
|
|
|
|
var (
|
|
|
|
token *jwt.Token
|
|
|
|
)
|
|
|
|
|
|
|
|
if nil == claims {
|
|
|
|
token = jwt.New(signMethod)
|
|
|
|
} else {
|
|
|
|
token = jwt.NewWithClaims(signMethod, claims)
|
|
|
|
}
|
2023-02-12 00:00:50 +08:00
|
|
|
return token.SignedString([]byte(secret))
|
2023-02-11 21:14:57 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Validate 验证token
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 20:13 2023/2/11
|
2023-02-12 00:36:24 +08:00
|
|
|
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")
|
|
|
|
}
|
2023-02-11 21:14:57 +08:00
|
|
|
var (
|
|
|
|
token *jwt.Token
|
|
|
|
err error
|
|
|
|
)
|
|
|
|
|
|
|
|
if token, err = jwt.Parse(inputToken, func(tokenInfo *jwt.Token) (interface{}, error) {
|
2023-02-12 00:00:50 +08:00
|
|
|
return []byte(secret), nil
|
2023-02-11 21:14:57 +08:00
|
|
|
}); nil != err {
|
2023-02-12 00:36:24 +08:00
|
|
|
return errors.New("token parse fail : " + err.Error())
|
2023-02-11 21:14:57 +08:00
|
|
|
}
|
|
|
|
if !token.Valid {
|
2023-02-12 00:36:24 +08:00
|
|
|
return errors.New("token is valid : " + err.Error())
|
|
|
|
}
|
|
|
|
if nil != convert {
|
|
|
|
if err = convert(token.Claims); nil != err {
|
|
|
|
return err
|
|
|
|
}
|
2023-02-11 21:14:57 +08:00
|
|
|
}
|
2023-02-12 00:36:24 +08:00
|
|
|
return nil
|
2023-02-11 21:14:57 +08:00
|
|
|
}
|