Home >Backend Development >Golang >How can I authenticate subsequent HTTP requests in Go after an initial authentication using basic auth?
Authenticated HTTP Client Requests from Go
Consider the following code snippet:
client := &http.Client{} /* Authenticate */ req, err := http.NewRequest("GET", "http://164.99.113.32/Authenticate", nil) req.SetBasicAuth("<username>", "<password>") resp, err := client.Do(req) if err != nil { fmt.Printf("Error : %s", err) } /* Get Details */ req.URL, _ = url.Parse("http://164.99.113.32/Details") resp, err = client.Do(req) if err != nil { fmt.Printf("Error : %s", err) }
The problem here is that the second HTTP call fails with a 401 access denied error.
Why does this happen?
The reason is that the second request does not contain the session cookie that was obtained during the first request. To solve this, we need to create a cookie jar to store and reuse cookies across requests.
type myjar struct { jar map[string] []*http.Cookie } func (p* myjar) SetCookies(u *url.URL, cookies []*http.Cookie) { fmt.Printf("The URL is : %s\n", u.String()) fmt.Printf("The cookie being set is : %s\n", cookies) p.jar [u.Host] = cookies } func (p *myjar) Cookies(u *url.URL) []*http.Cookie { fmt.Printf("The URL is : %s\n", u.String()) fmt.Printf("Cookie being returned is : %s\n", p.jar[u.Host]) return p.jar[u.Host] }
In the main function:
jar := &myjar{} jar.jar = make(map[string] []*http.Cookie) client.Jar = jar
With these changes, the second request will have the necessary cookie to successfully authenticate and retrieve the details from the server.
The above is the detailed content of How can I authenticate subsequent HTTP requests in Go after an initial authentication using basic auth?. For more information, please follow other related articles on the PHP Chinese website!