Skip to content

Instantly share code, notes, and snippets.

@federicobond
Created May 20, 2019 20:05
Show Gist options
  • Save federicobond/be91e878fcf83e4a3517b4dc07880ad1 to your computer and use it in GitHub Desktop.
Save federicobond/be91e878fcf83e4a3517b4dc07880ad1 to your computer and use it in GitHub Desktop.
Sign and verify JWT with Go
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"fmt"
"testing"
jwt "github.com/dgrijalva/jwt-go"
)
func TestSignVerifyJWT(t *testing.T) {
privkey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
pubkey := privkey.Public()
token := jwt.New(jwt.SigningMethodES256)
token.Claims = jwt.StandardClaims{
Subject: "foo",
}
tokenStr, err := token.SignedString(privkey)
if err != nil {
t.Fatal(err)
}
bytes := []byte("-----BEGIN PUBLIC KEY -----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEWOS4zeNb4rxSzYoqhRIOJaD8cxMjZg1/NDEiiVcbIoP+YvETTZFJmCDxaumwZnNYbozOy5jRWeheQMsw6WzLMg==\n-----END PUBLIC KEY -----")
_, err = jwt.ParseECPublicKeyFromPEM(bytes)
if err != nil {
t.Fatal(err)
}
token, err = jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
return pubkey, nil
})
if err != nil {
t.Fatal(err)
}
claims := token.Claims.(jwt.MapClaims)
if claims["sub"] != "foo" {
t.Fatal("expected claims.Subject to be foo")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment