首頁 > 後端開發 > Golang > 主體

在使用基本驗證進行初步驗證後,如何在 Go 中對後續 HTTP 請求進行驗證?

Barbara Streisand
發布: 2024-11-14 19:24:02
原創
487 人瀏覽過

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.

以上是在使用基本驗證進行初步驗證後,如何在 Go 中對後續 HTTP 請求進行驗證?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板