From 253c069b26a36694c553b5cf239ccc6e38af87a7 Mon Sep 17 00:00:00 2001 From: jordi collell Date: Fri, 8 May 2015 09:41:17 +0200 Subject: [PATCH] if basic auth fails should write unauthorized to response --- middleware/basicauth/basicauth.go | 1 + middleware/basicauth/basicauth_test.go | 15 ++++++++++++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/middleware/basicauth/basicauth.go b/middleware/basicauth/basicauth.go index de29b8d9..0ab92437 100644 --- a/middleware/basicauth/basicauth.go +++ b/middleware/basicauth/basicauth.go @@ -31,6 +31,7 @@ func (a BasicAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error // Check credentials if !ok || username != rule.Username || password != rule.Password { w.Header().Set("WWW-Authenticate", "Basic") + w.WriteHeader(http.StatusUnauthorized) return http.StatusUnauthorized, nil } diff --git a/middleware/basicauth/basicauth_test.go b/middleware/basicauth/basicauth_test.go index 7b551ba4..6ba34b65 100644 --- a/middleware/basicauth/basicauth_test.go +++ b/middleware/basicauth/basicauth_test.go @@ -24,12 +24,14 @@ func TestBasicAuth(t *testing.T) { result int cred string }{ + {"/testing", http.StatusUnauthorized, "ttest:test"}, {"/testing", http.StatusOK, "test:ttest"}, + {"/testing", http.StatusUnauthorized, ""}, } - //auth := "Basic " + base64.StdEncoding.EncodeToString([]byte("foo:bar")) + for i, test := range tests { @@ -41,7 +43,14 @@ func TestBasicAuth(t *testing.T) { req.Header.Set("Authorization", auth) rec := httptest.NewRecorder() - rw.ServeHTTP(rec, req) + result, err := rw.ServeHTTP(rec, req) + if err != nil { + t.Fatalf("Test %d: Could not ServeHTTP %v", i, err) + } + if result != test.result { + t.Errorf("Test %d: Expected Header '%d' but was '%d'", + i, test.result, result) + } if rec.Code != test.result { t.Errorf("Test %d: Expected Header '%d' but was '%d'", @@ -54,5 +63,5 @@ func TestBasicAuth(t *testing.T) { func contentHandler(w http.ResponseWriter, r *http.Request) (int, error) { fmt.Fprintf(w, r.URL.String()) - return 0, nil + return http.StatusOK, nil } \ No newline at end of file