Home  >  Article  >  Backend Development  >  Why Does Basic HTTP Authentication Fail in Go When Redirects Occur?

Why Does Basic HTTP Authentication Fail in Go When Redirects Occur?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-21 04:46:17327browse

Why Does Basic HTTP Authentication Fail in Go When Redirects Occur?

Basic HTTP Authentication Handling in Go

When implementing basic HTTP authentication in Go, some unexpected challenges may arise. This article delves into a common issue encountered when attempting to implement basic HTTP authentication.

Issue: An error stating "unsupported protocol scheme" is encountered when executing the following code:

func basicAuth() string {
    var username string = "foo"
    var passwd string = "bar"
    client := &http.Client{}
    req, err := http.NewRequest("GET", "mydomain.example", nil)
    req.SetBasicAuth(username, passwd)
    resp, err := client.Do(req)
    if err != nil{
        log.Fatal(err)
    }
    bodyText, err := ioutil.ReadAll(resp.Body)
    s := string(bodyText)
    return s
}

Cause: When redirects occur, Go-lang discards any specified headers, including the Authorization header set for basic authentication.

Solution: To rectify this issue, a custom redirect policy function can be implemented:

func redirectPolicyFunc(req *http.Request, via []*http.Request) error {
    req.Header.Add("Authorization", "Basic "+basicAuth("username1", "password123"))
    return nil
}

This function ensures that the Authorization header is added back during redirects, effectively preserving the authentication credentials.

Implementation:

func main() {
    client := &http.Client{
        Jar: cookieJar,
        CheckRedirect: redirectPolicyFunc,
    }
    req, err := http.NewRequest("GET", "http://localhost/", nil)
    req.Header.Add("Authorization", "Basic "+basicAuth("username1", "password123")) 
    resp, err := client.Do(req)
}

By utilizing the redirect policy function, the specified headers, including the Authorization header for basic authentication, will persist throughout redirects, ensuring successful authentication with the target server.

The above is the detailed content of Why Does Basic HTTP Authentication Fail in Go When Redirects Occur?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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