duanlie4621 2019-09-19 09:03
浏览 381
已采纳

JWT Go / Golang base64编码有效载荷产生不同的结果

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)
            }
        }
    }
}
  • 写回答

2条回答 默认 最新

  • douxianglu4370 2019-09-19 09:22
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改