Search code examples
gopostauthenticationnet-http

A POST request after the login request, still asks for a permission


I am trying to send two PostForm requests to a specified URL(webpage), which one of them is "login" and another one is "create a product". The problem is the second request(create a product) runs apart from the first request(login). That is why although the login runs successfully, the server sends me a permission error("You must be logged in first to create a product.")

I thought, it's because of concurrency, thus I used channels and even time package as well, but none of them had worked. Is there any solution to handle it?

func login(c chan string) {
    resp, _ := http.PostForm("http://example.com/login",
        url.Values{"username": {"sth"}, "password": {"sth"}})
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    time.Sleep(5000 * time.Millisecond)
    fmt.Printf("%v", string(body), "\n")
    c <- string(body)
}

func CreateProduct() {
    resp, _ := http.PostForm("http://example.com/product",
        url.Values{"name": {"sth"}})
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Printf("%v", string(body), "\n")
}

func main() {
    c := make(chan string)
    go login(c)
    str := <-c
    if str != "" {
        CreateProduct()
    }
}

Solution

  • You don't need or want channels for this.

    You need to send a cookie or an authorise header. Check what the docs for the service you're trying to use say sbout authentication.

    If you specify which service people might be able to help more, but as a general guideline - if an api it probably wants a token, if a web page it probably expects a cookie, but beware you may also need to get around csrf protection in that case.