dongneng5383 2019-09-06 19:01
浏览 72

用代码调用REST API。 标头数据未设置,因此REST API无法访问Cookie

I am building a REST API for authentication. I am setting a JSON web token as a cookie and retrieving it using a HTTP GET request. When I go to the location in my browser, it returns the JSON data from the cookie. However whenever I try to do my GET call in code, the header doesn't have the cookie so it doesn't work. It steps into the function, however it always returns "Error, unable to retrieve cookie" when I call it in code, and works when I go to the location in my browser.

//Relevant code

//Constants

const cookieName = "testCookie"
const getJWTPath = "/getJWT/"
const website = "http://localhost"
const port = ":8080"


//Payload JWT payload structure

type Payload struct {
    Uid            string   `json:"uid"`
    Ip             string   `json:"ip"`
    FacilityAccess []string `json:"facilityaccess"`
}

//HTTP Handler

func getJWT(w http.ResponseWriter, req *http.Request) {

    cookie, err := req.Cookie(cookieName)
    if err != nil {
        json.NewEncoder(w).Encode(Exception{"Error, unable to retrieve cookie"})
    } else {
        if validateCookieJWT(cookie) {
            //Pass JSON for payload into browser for GET result
            // 1. Get encoded payload from cookie JWT
            // 2. Create byte array from encoded payload
            // 3. Generate payload structure from byte array
            // 4. Validate payload, and return it to the browser if it is valid.
            jwtElements := strings.Split(cookie.Value, ".")
            encodedPayload := jwtElements[1] //Get encoded payload from cookie JWT

            payloadByte, err := base64.StdEncoding.DecodeString(encodedPayload) //Create byte array from encoded payload
            if err != nil {
                json.NewEncoder(w).Encode(Exception{"error decoding encoded payload"})
            } else {
                payload := Payload{}
                err := json.Unmarshal(payloadByte, &payload) //Create payload structure from payload byte array
                if err != nil {
                    json.NewEncoder(w).Encode(Exception{"Error unmarshalling payloadByte"})
                } else {

                    json.NewEncoder(w).Encode(payload) //Return payload to the browser
                }
            }
        } else {
            json.NewEncoder(w).Encode(Exception{"Unable to validate jwt"})
        }
    }
}

//Calling rest API in code, for some reason does not have cookies in request header

func validJWT(r *http.Request) bool {
    getJWTurl := website + port + getJWTPath

    req, err := http.NewRequest(http.MethodGet, getJWTurl, nil)
    if err != nil {
        return false
    }

    client := &http.Client{}

    resp, err := client.Do(req)
    if err != nil {
        return false
    }

    defer resp.Body.Close()

    var payload Payload
    if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
        return false
    }

    return payload.id != ""
}

In the method getJWT, after I call: cookie, err:= req.Cookie(cookieName), err returns the following: "http: named cookie not present"

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 stata安慰剂检验作图但是真实值不出现在图上
    • ¥15 c程序不知道为什么得不到结果
    • ¥40 复杂的限制性的商函数处理
    • ¥15 程序不包含适用于入口点的静态Main方法
    • ¥15 素材场景中光线烘焙后灯光失效
    • ¥15 请教一下各位,为什么我这个没有实现模拟点击
    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
    • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥85 永磁型步进电机PID算法