42 lines
1014 B
Go
42 lines
1014 B
Go
package jwt
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
type Claims struct {
|
|
UserId string `json:"userId"`
|
|
RoleKey string `json:"roleKey"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
func GenerateToken(secret string, expire int64, userId, roleKey string) (string, error) {
|
|
now := time.Now()
|
|
claims := Claims{
|
|
UserId: userId,
|
|
RoleKey: roleKey,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
ExpiresAt: jwt.NewNumericDate(now.Add(time.Duration(expire) * time.Second)),
|
|
IssuedAt: jwt.NewNumericDate(now),
|
|
NotBefore: jwt.NewNumericDate(now),
|
|
},
|
|
}
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
return token.SignedString([]byte(secret))
|
|
}
|
|
|
|
func ParseToken(tokenStr, secret string) (*Claims, error) {
|
|
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(t *jwt.Token) (interface{}, error) {
|
|
return []byte(secret), nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
|
|
return claims, nil
|
|
}
|
|
return nil, jwt.ErrTokenInvalidClaims
|
|
}
|