01/11/2020 - GO
In this example we are going to create a JWT token using HMAC HS256 signature and validate it. HSA is a symmetric signing method which uses only a secret key. Use this only if both creator (server app) and user (client app) of tokens are 100% trusted. In doubt, prefer RSA instead where private and public keys are used.
You can use something like this or this to create a secret.
package main
import (
"fmt"
"log"
"time"
"github.com/you/auth/internal/pkg/token"
)
func main() {
// You can inject this instance to where you need it.
jwtToken := token.NewJWT([]byte("your-256-bit-static-secret"))
// 1. Create a new JWT token.
tok, err := jwtToken.Create(time.Hour, "Can be anything")
if err != nil {
log.Fatalln(err)
}
fmt.Println("TOKEN:", tok)
// 2. Validate an existing JWT token.
content, err := jwtToken.Validate(tok)
if err != nil {
log.Fatalln(err)
}
fmt.Println("CONTENT:", content)
}
package token
import (
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
)
type JWT struct {
key []byte
}
func NewJWT(key []byte) JWT {
return JWT{
key: key,
}
}
func (j JWT) Create(ttl time.Duration, content interface{}) (string, error) {
now := time.Now().UTC()
claims := make(jwt.MapClaims)
claims["dat"] = content // Our custom data.
claims["exp"] = now.Add(ttl).Unix() // The expiration time after which the token must be disregarded.
claims["iat"] = now.Unix() // The time at which the token was issued.
claims["nbf"] = now.Unix() // The time before which the token must be disregarded.
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(j.key)
if err != nil {
return "", fmt.Errorf("create: %w", err)
}
return token, nil
}
func (j JWT) Validate(token string) (interface{}, error) {
tok, err := jwt.Parse(token, func(jwtToken *jwt.Token) (interface{}, error) {
if _, ok := jwtToken.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected method: %s", jwtToken.Header["alg"])
}
return j.key, nil
})
if err != nil {
return nil, fmt.Errorf("validate: %w", err)
}
claims, ok := tok.Claims.(jwt.MapClaims)
if !ok || !tok.Valid {
return nil, fmt.Errorf("validate: invalid")
}
return claims["dat"], nil
}
Use jwt.io to decode the token and JSON Web Token (JWT) for more information about JWT in general.
$ go run -race main.go
TOKEN: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXQiOiJDYW4gYmUgYW55dGhpbmciLCJleHAiOjE2MDQyNDAxMDUsImlhdCI6MTYwNDIzNjUwNSwibmJmIjoxNjA0MjM2NTA1fQ.iEkDvKJ2fscx20SDSM6QGxAe6S0nJYA9KTLZDTiiXVc
CONTENT: Can be anything