1

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)
            }
        }
    }
}
Arne Winter
  • 13
  • 1
  • 4

2 Answers2

0

The difference comes simply from the library "compacting" the JSON before applying Base64 encoding.

See this example:

ss := []string{
    `{"exp": 4724377561}`,
    `{"exp":4724377561}`,
}
for _, s := range ss {
    fmt.Println(base64.RawURLEncoding.EncodeToString([]byte(s)), s)
}

Output (try it on the Go Playground):

eyJleHAiOiA0NzI0Mzc3NTYxfQ {"exp": 4724377561}
eyJleHAiOjQ3MjQzNzc1NjF9 {"exp":4724377561}

The second output matches what you expect. To remove insignificant whitespace in Go use json.Compact.

Peter
  • 29,454
  • 5
  • 48
  • 60
icza
  • 389,944
  • 63
  • 907
  • 827
0

converting back the encoded strings on https://www.base64decode.org/ tells you what's going on:

ewogICAiZXhwIjogNDcyNDM3NzU2MQp9

is decoded to

{
"exp": 4724377561
}

while the jwt.io string is decoded to

{"exp":4724377561}

so https://jwt.io trims all whitespace and linebreaks before encoding.

jps
  • 20,041
  • 15
  • 75
  • 79