Codebase list golang-github-go-kit-kit / 355d3e3
improve error handling and style Dmitry Salakhov 6 years ago
3 changed file(s) with 16 addition(s) and 5 deletion(s). Raw diff Collapse all Expand all
0 `package auth/basic` provides a Basic Authentication middleware [Mozilla article](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
0 This package provides a Basic Authentication middleware.
1
2 It'll try to compare credentials from Authentication request header to a username/password pair in middleware constructor.
3
4 More details about this type of authentication can be found in [Mozilla article](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
15
26 ## Usage
37
59 import httptransport "github.com/go-kit/kit/transport/http"
610
711 httptransport.NewServer(
8 endpoint.Chain(AuthMiddleware(cfg.auth.user, cfg.auth.password, "Example Realm"))(makeUppercaseEndpoint()),
12 AuthMiddleware(cfg.auth.user, cfg.auth.password, "Example Realm")(makeUppercaseEndpoint()),
913 decodeMappingsRequest,
1014 httptransport.EncodeJSONResponse,
1115 httptransport.ServerBefore(httptransport.PopulateRequestContext),
3333 return http.Header{
3434 "Content-Type": []string{"text/plain; charset=utf-8"},
3535 "X-Content-Type-Options": []string{"nosniff"},
36 "WWW-Authenticate": []string{fmt.Sprintf(`Basic realm=%q`, e.Realm)}}
36 "WWW-Authenticate": []string{fmt.Sprintf(`Basic realm=%q`, e.Realm)},
37 }
3738 }
3839
3940 // parseBasicAuth parses an HTTP Basic Authentication string.
6869
6970 return func(next endpoint.Endpoint) endpoint.Endpoint {
7071 return func(ctx context.Context, request interface{}) (interface{}, error) {
71 auth := ctx.Value(httptransport.ContextKeyRequestAuthorization).(string)
72 auth, ok := ctx.Value(httptransport.ContextKeyRequestAuthorization).(string)
73 if !ok {
74 return nil, AuthError{realm}
75 }
76
7277 givenUser, givenPassword, ok := parseBasicAuth(auth)
7378 if !ok {
7479 return nil, AuthError{realm}
1919 }
2020 tests := []struct {
2121 name string
22 authHeader string
22 authHeader interface{}
2323 want want
2424 }{
25 {"Isn't valid with nil header", nil, want{nil, AuthError{realm}}},
26 {"Isn't valid with non-string header", 42, want{nil, AuthError{realm}}},
2527 {"Isn't valid without authHeader", "", want{nil, AuthError{realm}}},
2628 {"Isn't valid for wrong user", makeAuthString("wrong-user", requiredPassword), want{nil, AuthError{realm}}},
2729 {"Isn't valid for wrong password", makeAuthString(requiredUser, "wrong-password"), want{nil, AuthError{realm}}},