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"