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条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘