65 lines
1.2 KiB
Go
65 lines
1.2 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"
|
||
|
)
|
||
|
|
||
|
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(secret)
|
||
|
}
|
||
|
|
||
|
// Validate 验证token
|
||
|
//
|
||
|
// Author : go_developer@163.com<白茶清欢>
|
||
|
//
|
||
|
// Date : 20:13 2023/2/11
|
||
|
func (j *ownJwt) Validate(inputToken string, secret string) (jwt.Claims, error) {
|
||
|
var (
|
||
|
token *jwt.Token
|
||
|
err error
|
||
|
)
|
||
|
|
||
|
if token, err = jwt.Parse(inputToken, func(tokenInfo *jwt.Token) (interface{}, error) {
|
||
|
return 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
|
||
|
}
|