diff --git a/auth/basic/README.md b/auth/basic/README.md index b681ac7..26d6c4b 100644 --- a/auth/basic/README.md +++ b/auth/basic/README.md @@ -1,4 +1,8 @@ -`package auth/basic` provides a Basic Authentication middleware [Mozilla article](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). +This package provides a Basic Authentication middleware. + +It'll try to compare credentials from Authentication request header to a username/password pair in middleware constructor. + +More details about this type of authentication can be found in [Mozilla article](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). ## Usage @@ -6,7 +10,7 @@ import httptransport "github.com/go-kit/kit/transport/http" httptransport.NewServer( - endpoint.Chain(AuthMiddleware(cfg.auth.user, cfg.auth.password, "Example Realm"))(makeUppercaseEndpoint()), + AuthMiddleware(cfg.auth.user, cfg.auth.password, "Example Realm")(makeUppercaseEndpoint()), decodeMappingsRequest, httptransport.EncodeJSONResponse, httptransport.ServerBefore(httptransport.PopulateRequestContext), diff --git a/auth/basic/middleware.go b/auth/basic/middleware.go index eeb2317..ad7e408 100644 --- a/auth/basic/middleware.go +++ b/auth/basic/middleware.go @@ -34,7 +34,8 @@ return http.Header{ "Content-Type": []string{"text/plain; charset=utf-8"}, "X-Content-Type-Options": []string{"nosniff"}, - "WWW-Authenticate": []string{fmt.Sprintf(`Basic realm=%q`, e.Realm)}} + "WWW-Authenticate": []string{fmt.Sprintf(`Basic realm=%q`, e.Realm)}, + } } // parseBasicAuth parses an HTTP Basic Authentication string. @@ -69,7 +70,11 @@ return func(next endpoint.Endpoint) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { - auth := ctx.Value(httptransport.ContextKeyRequestAuthorization).(string) + auth, ok := ctx.Value(httptransport.ContextKeyRequestAuthorization).(string) + if !ok { + return nil, AuthError{realm} + } + givenUser, givenPassword, ok := parseBasicAuth(auth) if !ok { return nil, AuthError{realm} diff --git a/auth/basic/middleware_test.go b/auth/basic/middleware_test.go index a34c6cf..9ad330e 100644 --- a/auth/basic/middleware_test.go +++ b/auth/basic/middleware_test.go @@ -20,9 +20,11 @@ } tests := []struct { name string - authHeader string + authHeader interface{} want want }{ + {"Isn't valid with nil header", nil, want{nil, AuthError{realm}}}, + {"Isn't valid with non-string header", 42, want{nil, AuthError{realm}}}, {"Isn't valid without authHeader", "", want{nil, AuthError{realm}}}, {"Isn't valid for wrong user", makeAuthString("wrong-user", requiredPassword), want{nil, AuthError{realm}}}, {"Isn't valid for wrong password", makeAuthString(requiredUser, "wrong-password"), want{nil, AuthError{realm}}},