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 54 55 56 57 58 59
| package main
import ( "errors" "fmt" "time"
"github.com/golang-jwt/jwt/v4" )
type TokenClaims struct { jwt.RegisteredClaims }
func main() { key := []byte("256-bit-key")
token, err := CreateToken(key) if err != nil { fmt.Println(err) } fmt.Println(token)
parsed, err := ParseToken(token, key) if err != nil { fmt.Println(err) } fmt.Println(parsed) }
func CreateToken(key []byte) (string, error) { duration := 24 * time.Hour claims := TokenClaims{ jwt.RegisteredClaims{ ExpiresAt: jwt.NewNumericDate(time.Now().Add(duration)), }, } token := jwt.NewWithClaims(jwt.SigningMethodHS256, &claims) ss, err := token.SignedString(key) if err != nil { return "", err } return ss, nil }
func ParseToken(tokenString string, key []byte) (*TokenClaims, error) { token, err := jwt.ParseWithClaims(tokenString, &TokenClaims{}, func(token *jwt.Token) (i interface{}, err error) { return key, nil }) if err != nil { return nil, err } if claims, ok := token.Claims.(*TokenClaims); ok && token.Valid { return claims, nil } return nil, errors.New("invalid token") }
|