Skip to content

Commit

Permalink
Add basic auth support: Sling.SetBasicAuth()
Browse files Browse the repository at this point in the history
  • Loading branch information
AaronO authored and dghubble committed Jun 14, 2016
1 parent 5765fe1 commit c1694aa
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
15 changes: 15 additions & 0 deletions sling.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package sling

import (
"bytes"
"encoding/base64"
"encoding/json"
"io"
"io/ioutil"
Expand Down Expand Up @@ -145,6 +146,20 @@ func (s *Sling) Set(key, value string) *Sling {
return s
}

// SetBasicAuth sets the Authorization header to use HTTP Basic Authentication
// with the provided username and password. With HTTP Basic Authentication
// the provided username and password are not encrypted.
func (s *Sling) SetBasicAuth(username, password string) *Sling {
return s.Set("Authorization", "Basic "+basicAuth(username, password))
}

// basicAuth returns the base64 encoded username:password for basic auth copied
// from net/http.
func basicAuth(username, password string) string {
auth := username + ":" + password
return base64.StdEncoding.EncodeToString([]byte(auth))
}

// Url

// Base sets the rawURL. If you intend to extend the url with Path,
Expand Down
28 changes: 28 additions & 0 deletions sling_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,34 @@ func TestSetHeader(t *testing.T) {
}
}

func TestBasicAuth(t *testing.T) {
cases := []struct {
sling *Sling
expectedAuth []string
}{
// basic auth: username & password
{New().SetBasicAuth("Aladdin", "open sesame"), []string{"Aladdin", "open sesame"}},
// empty username
{New().SetBasicAuth("", "secret"), []string{"", "secret"}},
// empty password
{New().SetBasicAuth("admin", ""), []string{"admin", ""}},
}
for _, c := range cases {
req, err := c.sling.Request()
if err != nil {
t.Errorf("unexpected error when building Request with .SetBasicAuth()")
}
username, password, ok := req.BasicAuth()
if !ok {
t.Errorf("basic auth missing when expected")
}
auth := []string{username, password}
if !reflect.DeepEqual(c.expectedAuth, auth) {
t.Errorf("not DeepEqual: expected %v, got %v", c.expectedAuth, auth)
}
}
}

func TestQueryStructSetter(t *testing.T) {
cases := []struct {
sling *Sling
Expand Down

0 comments on commit c1694aa

Please sign in to comment.