1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
package jwt
import ( "errors" "github.com/golang-jwt/jwt/v4" "time" )
type JwtPayload struct { UserID uint `json:"user_id"` Username string `json:"username"` }
type MyCustomClaims struct { JwtPayload jwt.RegisteredClaims }
func CreateJwtToken(jwtPayload JwtPayload, accessSecret string, expires int64) (string, error) { claims := MyCustomClaims{ JwtPayload: jwtPayload, RegisteredClaims: jwt.RegisteredClaims{ ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * time.Duration(expires))), }, }
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) return token.SignedString([]byte(accessSecret)) }
func ParseJwtToken(tokenString string, accessSecret string) (*MyCustomClaims, error) { token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) { return []byte(accessSecret), nil }) if err != nil { return nil, err } if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid { return claims, nil } return nil, errors.New("invalid jwt token") }
|