duanpuchun5275 2019-08-22 14:01
浏览 122
已采纳

将JWT有效负载转换回结构

I'm having trouble converting a JWT payload back to a struct in golang

I have two servers which communicate with each other and have a JWT auth to enforce security.

The payloads use the below struct

type ResponseBody struct {
    Header       dto.MessageHeader       `json:"message_header"`
    OrderBodyParams dto.OrderBodyParams `json:"order_response"`
    Status              string                  `json:"status"`
    ErrorMessage        string                  `json:"errors"`
}

Server A takes this struct - converts it into byte date and sends it as a JWT payload

the relevant code is below

func request(secretKey string, path string, method string, requestParams interface{}, response interface{}) error {

    tr := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
    client := &http.Client{
        Timeout:   time.Second * 15,
        Transport: tr,
    }

    //convert body into byte data
    requestBody, err := json.Marshal(requestParams)
    if err != nil {
        return err
    }

    tokenString, expirationTime, err := authentication.GenerateJWTAuthToken(secretKey, requestBody)
    if err != nil {
      return err
    }

    req, _ := http.NewRequest(method, path, bytes.NewBuffer([]byte(tokenString)))
    req.Header.Set("Content-Type", "application/json")
    req.AddCookie(&http.Cookie{
        Name:    "token",
        Value:   tokenString,
        Expires: expirationTime,
    })

    _, err = client.Do(req)

    if err != nil {
       return err
    }

    return nil
}

As you can see , i'm merely converting the body to byte data - and converting it into a JWT payload

the function GenerateJWTAuthToken is like the below

type Claims struct {
    Payload []byte `json:"payload"`
    jwt.StandardClaims
}


func GenerateJWTAuthToken(secretKey string, payload []byte) (string, time.Time, error) {
    var jwtKey = []byte(secretKey)

    // Set expiration to 5 minutes from now (Maybe lesser?)
    expirationTime := time.Now().Add(5 * time.Minute)
    // create the payload
    claims := &Claims{
        Payload: payload,
        StandardClaims: jwt.StandardClaims{
            ExpiresAt: expirationTime.Unix(),
        },
    }

    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    tokenString, err := token.SignedString(jwtKey)

    if err != nil {
        return "", time.Time{}, fmt.Errorf("Error generating JWT token : %+v", err)
    }
    return tokenString, expirationTime, nil
}

Now server B - recieves the data and validates the JWT and converts the byte payload back to the ResponseBody struct

func Postback(appState *appsetup.AppState) http.HandlerFunc {
    fn := func(w http.ResponseWriter, r *http.Request) {

        body, err := ioutil.ReadAll(r.Body)
        tokenString := string(body)
        if err != nil {
            w.WriteHeader(http.StatusUnauthorized)
            return
        }

        // Verify the JWT token send from server A and ensure its a valid request
        // If the token is invalid , dont proceed further
        token, payload, err := authentication.VerifyJWTToken(appState.SecretKey, tokenString)

        if err != nil {
            if err == jwt.ErrSignatureInvalid {
                w.WriteHeader(http.StatusUnauthorized)
                return
            }
            w.WriteHeader(http.StatusBadRequest)
            return
        }
        if !token.Valid {
            w.WriteHeader(http.StatusUnauthorized)
            return
        }


        requestData := ResponseBody{}
        err = binary.Read(bytes.NewReader(payload), binary.LittleEndian, &requestData)
        if err != nil {
            fmt.Printf("Couldnt convert payload body to struct : %+v ", err)
            return
        }
        return requestData
    }
    return http.HandlerFunc(fn)
}

The VerifyJWTToken function is pretty straightforward as well (i'm hoping)

func VerifyJWTToken(secretKey string, tokenString string) (*jwt.Token, []byte, error) {
    var jwtKey = []byte(secretKey)
    var payload []byte
    claims := &Claims{}

    token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {

        if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
            return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
        }

        return jwtKey, nil
    })

    if err != nil {
        return nil, payload, err
    }

    return token, claims.Payload, nil
}

But i'm having trouble converting the payload back to the ResponseBody struct -

It seems to fail at the line err = binary.Read(bytes.NewReader(bodyBuffer), binary.LittleEndian, &requestData)

with the below error

msg":"Couldnt convert payload body to struct : binary.Read: invalid type *ResponseBody "

Is there something i'm missing?

  • 写回答

1条回答 默认 最新

  • dsbc80836 2019-08-22 14:31
    关注

    You're using JSON to marshal your struct:

    requestBody, err := json.Marshal(requestParams)`
    

    So you should use JSON unmarshaling to get back the struct. Yet, you're using binary.Read() to read it:

    err = binary.Read(bytes.NewReader(payload), binary.LittleEndian, &requestData)
    

    Instead do it like this:

    err = json.Unmarshal(payload, &requestData)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题