Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic HTTP Auth in Go

I'm trying to do basic HTTP auth with the code below, but it is throwing out the following error:

2013/05/21 10:22:58 Get mydomain.com: unsupported protocol scheme "" exit status 1

func basicAuth() string {     var username string = "foo"     var passwd string = "bar"     client := &http.Client{}     req, err := http.NewRequest("GET", "mydomain.com", 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 } 

Any idea what I may be doing wrong?

like image 739
leonsas Avatar asked May 21 '13 15:05

leonsas


People also ask

How do you implement basic auth in Golang?

Creating the HTTP server Now we will add a check for basic auth in the greeting handler. If you look at the above carefully, you will see we are using the r. BasicAuth() method to extract the username password. Here is the method signature func (r *Request) BasicAuth() (username, password string, ok bool) .

What does HTTP Basic Auth do?

HTTP basic authentication is a simple challenge and response mechanism with which a server can request authentication information (a user ID and password) from a client. The client passes the authentication information to the server in an Authorization header. The authentication information is in base-64 encoding.

How do I add basic auth to swagger?

Basic authentication is easy to define. In the global securityDefinitions section, add an entry with type: basic and an arbitrary name (in this example - basicAuth). Then, apply security to the whole API or specific operations by using the security section.


1 Answers

the potential 'gotcha' is if your website does any redirects... Go-lang will drop your specified headers on the redirects. (I had to do wireshark to see this! You can quicky find out in chrome by right-clicking then "inspect element" and click network tab)

you'll want to define a redirect function that adds the header back in.

func basicAuth(username, password string) string {   auth := username + ":" + password   return base64.StdEncoding.EncodeToString([]byte(auth)) }  func redirectPolicyFunc(req *http.Request, via []*http.Request) error{   req.Header.Add("Authorization","Basic " + basicAuth("username1","password123"))   return nil }  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) } 
like image 72
pmerrell Avatar answered Sep 29 '22 19:09

pmerrell