From 691ebb382ef5ecf23d87cd6b98e132c275163318 Mon Sep 17 00:00:00 2001 From: Maxim Eremenko Date: Wed, 6 Mar 2019 15:31:00 +0300 Subject: [PATCH] Add Basic Auth --- request.go | 17 +++++++++++++++++ request_test.go | 6 ++++++ 2 files changed, 23 insertions(+) diff --git a/request.go b/request.go index 7e2fe77..6302c4e 100644 --- a/request.go +++ b/request.go @@ -1,6 +1,7 @@ package gock import ( + "encoding/base64" "io" "io/ioutil" "net/http" @@ -182,6 +183,12 @@ func (r *Request) MatchType(kind string) *Request { return r } +// BasicAuth defines a username and password for HTTP Basic Authentication +func (r *Request) BasicAuth(username, password string) *Request { + r.Header.Set("Authorization", "Basic "+basicAuth(username, password)) + return r +} + // MatchHeader defines a new key and value header to match. func (r *Request) MatchHeader(key, value string) *Request { r.Header.Set(key, value) @@ -297,3 +304,13 @@ func (r *Request) ReplyFunc(replier func(*Response)) *Response { replier(r.Response) return r.Response } + +// See 2 (end of page 4) https://www.ietf.org/rfc/rfc2617.txt +// "To receive authorization, the client sends the userid and password, +// separated by a single colon (":") character, within a base64 +// encoded string in the credentials." +// It is not meant to be urlencoded. +func basicAuth(username, password string) string { + auth := username + ":" + password + return base64.StdEncoding.EncodeToString([]byte(auth)) +} diff --git a/request_test.go b/request_test.go index 33e475f..5334ca1 100644 --- a/request_test.go +++ b/request_test.go @@ -84,6 +84,12 @@ func TestRequestMatchType(t *testing.T) { st.Expect(t, req.Header.Get("Content-Type"), "foo/bar") } +func TestRequestBasicAuth(t *testing.T) { + req := NewRequest() + req.BasicAuth("bob", "qwerty") + st.Expect(t, req.Header.Get("Authorization"), "Basic Ym9iOnF3ZXJ0eQ==") +} + func TestRequestMatchHeader(t *testing.T) { req := NewRequest() req.MatchHeader("foo", "bar")