46 lines
1.2 KiB
Go
46 lines
1.2 KiB
Go
package tokenx
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"errors"
|
||
|
|
"fmt"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"github.com/golang-jwt/jwt/v4"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Claims JWT 自定义负载
|
||
|
|
type Claims struct {
|
||
|
|
UserId int `json:"userId"`
|
||
|
|
Username string `json:"username"`
|
||
|
|
Name string `json:"name"`
|
||
|
|
RoleId int `json:"roleId"`
|
||
|
|
RoleCode string `json:"roleCode"`
|
||
|
|
RoleName string `json:"roleName"`
|
||
|
|
jwt.RegisteredClaims
|
||
|
|
}
|
||
|
|
|
||
|
|
// Issue 签发 JWT
|
||
|
|
func Issue(secret string, expire time.Duration, c Claims) (string, error) {
|
||
|
|
c.IssuedAt = jwt.NewNumericDate(time.Now())
|
||
|
|
c.ExpiresAt = jwt.NewNumericDate(time.Now().Add(expire))
|
||
|
|
c.Subject = fmt.Sprintf("%d", c.UserId)
|
||
|
|
t := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
|
||
|
|
return t.SignedString([]byte(secret))
|
||
|
|
}
|
||
|
|
|
||
|
|
// Parse 校验 JWT 并返回负载
|
||
|
|
func Parse(secret, tokenStr string) (*Claims, error) {
|
||
|
|
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(t *jwt.Token) (any, error) {
|
||
|
|
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||
|
|
return nil, errors.New("unexpected signing method")
|
||
|
|
}
|
||
|
|
return []byte(secret), nil
|
||
|
|
})
|
||
|
|
if err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
|
||
|
|
return claims, nil
|
||
|
|
}
|
||
|
|
return nil, errors.New("invalid token")
|
||
|
|
}
|