Skip to content

Instantly share code, notes, and snippets.

@john-yuan
Created April 23, 2023 09:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save john-yuan/2a1a7c0edcbfcb6bad454b438c5287cb to your computer and use it in GitHub Desktop.
Save john-yuan/2a1a7c0edcbfcb6bad454b438c5287cb to your computer and use it in GitHub Desktop.
Golang JWT Example. https://go.dev/play/p/RLiv9cD0f5-
package main
import (
"errors"
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
)
func Sign(key []byte, val string, ttl int64) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"val": val,
"exp": time.Now().Unix() + ttl,
})
return token.SignedString(key)
}
func Parse(key []byte, token string) (string, error) {
t, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
}
return key, nil
})
if claims, ok := t.Claims.(jwt.MapClaims); ok && t.Valid {
val, exists := claims["val"]
if !exists {
return "", errors.New("the field val does not exist")
}
return val.(string), nil
}
return "", errors.Join(err, errors.New("invalid token"))
}
func main() {
secret := "the jwt secret"
value := "The value to store in the token."
token, err := Sign([]byte(secret), value, 1800)
fmt.Println("Token:", token, err)
result, err := Parse([]byte(secret), token)
fmt.Println("Result:", result, err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment