67 lines
1.3 KiB
Go
67 lines
1.3 KiB
Go
|
// 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/v4"
|
||
|
)
|
||
|
|
||
|
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)
|
||
|
}
|
||
|
return token.SignedString([]byte(secret))
|
||
|
}
|
||
|
|
||
|
// Validate 验证token
|
||
|
//
|
||
|
// Author : go_developer@163.com<白茶清欢>
|
||
|
//
|
||
|
// Date : 20:13 2023/2/11
|
||
|
func (j *ownJwt) Validate(inputToken string, secret string, claims jwt.Claims) (jwt.Claims, error) {
|
||
|
|
||
|
var (
|
||
|
token *jwt.Token
|
||
|
err error
|
||
|
)
|
||
|
|
||
|
if token, err = jwt.ParseWithClaims(inputToken, claims, func(tokenInfo *jwt.Token) (interface{}, error) {
|
||
|
return []byte(secret), nil
|
||
|
}); nil != err {
|
||
|
return nil, errors.New("token parse fail : " + err.Error())
|
||
|
}
|
||
|
if !token.Valid {
|
||
|
return nil, errors.New("token is valid : " + err.Error())
|
||
|
}
|
||
|
|
||
|
return token.Claims, nil
|
||
|
}
|