44 lines
1.1 KiB
Go
Raw Normal View History

package jwt
import (
"time"
"github.com/golang-jwt/jwt/v5"
)
type Claims struct {
UserId string `json:"userId"`
RoleKey string `json:"roleKey"`
TenantId string `json:"tenantId"`
jwt.RegisteredClaims
}
func GenerateToken(secret string, expire int64, userId, roleKey, tenantId string) (string, error) {
now := time.Now()
claims := Claims{
UserId: userId,
RoleKey: roleKey,
TenantId: tenantId,
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
}