i have the following JWT payload:
{"exp": 4724377561}
(some date 100 years from now)
Encoding it in Go yields ewogICAiZXhwIjogNDcyNDM3NzU2MQp9
Using jwt.io it is however encoded to eyJleHAiOjQ3MjQzNzc1NjF9
which yields a different signature when signed. I use jwt.io's signatures in test fixtures.
I would like to not use 3rd party JWT tools, to keep my dependencies slim. I am suspecting some sort of character encoding is the issue here.
To keep the tests readable, I am using plain-text JSON in the fixtures.
The way i use my test fixtures is the following (omitting other test cases):
import (
"encoding/base64"
"reflect"
"testing"
)
var testData = []struct {
name string
header string
payload string
signature string
pass bool
errorType reflect.Type
}{{
name: "Succeed if token not expired",
header: `{"typ":"JWT","alg":"HS256"}`,
payload: `{"exp": 4724377561}`,
signature: "JHtMKvPSMa5BD22BsbxiP1-ELRh1XkIKkarRSev0ZjU",
pass: true,
}}
func TestParseJwt(t *testing.T) {
HmacSecret = []byte("My super secret key")
for _, tst := range testData {
jwt64 :=
base64.RawURLEncoding.EncodeToString([]byte(tst.header)) + "." +
base64.RawURLEncoding.EncodeToString([]byte(tst.payload)) + "." +
tst.signature
_, err := ParseJwt(jwt64)
if tst.pass {
if err != nil {
t.Fatal(tst.name, err)
}
} else {
// If an error was expected to be thrown, assert that it is the correct one.
if reflect.TypeOf(err).String() != tst.errorType.String() {
t.Fatal(tst.name, err)
}
}
}
}