兼容 两种写法
This commit is contained in:
27
utils/auth/auth.go
Normal file
27
utils/auth/auth.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func ParseToken(tokenstring string, password string, payload jwt.Claims) error {
|
||||
|
||||
_, err := jwt.ParseWithClaims(tokenstring, payload, func(t *jwt.Token) (interface{}, error) {
|
||||
// 验证令牌的签名方法
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
||||
}
|
||||
return []byte(password), nil
|
||||
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func SignToken(password string, payload jwt.Claims) (tokenstring string, err error) {
|
||||
return jwt.NewWithClaims(jwt.SigningMethodHS256, payload).SignedString([]byte(password))
|
||||
}
|
||||
34
utils/auth/auth_test.go
Normal file
34
utils/auth/auth_test.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"log"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type VestMoreClaims struct {
|
||||
CustomerId int64 `json:"customer_id"`
|
||||
Version string `json:"version"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func TestSignTokenAndParseToken(t *testing.T) {
|
||||
pwdhash := "123131"
|
||||
vm := &VestMoreClaims{
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().UTC().Add(1 * time.Hour)), // 设置过期时间为当前时间加24小时
|
||||
Issuer: "vermore",
|
||||
},
|
||||
}
|
||||
tstr, err := SignToken(pwdhash, vm)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
log.Println(tstr)
|
||||
vmr := &VestMoreClaims{}
|
||||
log.Println(ParseToken(tstr, pwdhash, vmr))
|
||||
log.Println(vmr)
|
||||
}
|
||||
Reference in New Issue
Block a user