Home > Backend Development > Golang > How can I authenticate subsequent HTTP requests in Go after an initial authentication using basic auth?

How can I authenticate subsequent HTTP requests in Go after an initial authentication using basic auth?

Barbara Streisand
Release: 2024-11-14 19:24:02
Original
560 people have browsed it

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)
}
Copy after login

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]
}
Copy after login

In the main function:

    jar := &myjar{}
    jar.jar = make(map[string] []*http.Cookie)
    client.Jar = jar
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template