Featured image of post JWT

JWT

JSON Web Tokens

import

1
import "github.com/golang-jwt/jwt/v5"

custom struct

1
2
3
4
type myClaims struct {
	jwt.RegisteredClaims
	Foo string `json:"foo"`
}

New token

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
tok = jwt.NewWithClaims(jwt.SigningMethodHS256, myClaims{
	RegisteredClaims: jwt.RegisteredClaims{
		Issuer:    "svc",
		Subject:   "user_id",
		Audience:  jwt.ClaimStrings{"srv"},
		ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Second * 2)),
		NotBefore: jwt.NewNumericDate(time.Now().Add(time.Second)),
		IssuedAt:  jwt.NewNumericDate(time.Now()),
		ID:        "id",
	},
	Foo: "bar",
})

Sign jwt string

1
2
3
4
s, err := tok.SignedString(key)
if err != nil {
	panic(err)
}

Parse

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
parsedTok, err := jwt.Parse(s, func(token *jwt.Token) (interface{}, error) {
	if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
		return nil, jwt.ErrInvalidKey
	}
	if token.Method.Alg() != jwt.SigningMethodHS256.Alg() {
		return nil, jwt.ErrInvalidKey
	}

	return key, nil
})
if err != nil {
	panic(err)
}
Licensed under CC BY-NC-SA 4.0