improve error handling and style
Dmitry Salakhov
6 years ago
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).
|
1 | 5 |
|
2 | 6 |
## Usage
|
3 | 7 |
|
|
5 | 9 |
import httptransport "github.com/go-kit/kit/transport/http"
|
6 | 10 |
|
7 | 11 |
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()),
|
9 | 13 |
decodeMappingsRequest,
|
10 | 14 |
httptransport.EncodeJSONResponse,
|
11 | 15 |
httptransport.ServerBefore(httptransport.PopulateRequestContext),
|
33 | 33 |
return http.Header{
|
34 | 34 |
"Content-Type": []string{"text/plain; charset=utf-8"},
|
35 | 35 |
"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 |
}
|
37 | 38 |
}
|
38 | 39 |
|
39 | 40 |
// parseBasicAuth parses an HTTP Basic Authentication string.
|
|
68 | 69 |
|
69 | 70 |
return func(next endpoint.Endpoint) endpoint.Endpoint {
|
70 | 71 |
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 |
|
72 | 77 |
givenUser, givenPassword, ok := parseBasicAuth(auth)
|
73 | 78 |
if !ok {
|
74 | 79 |
return nil, AuthError{realm}
|
19 | 19 |
}
|
20 | 20 |
tests := []struct {
|
21 | 21 |
name string
|
22 | |
authHeader string
|
|
22 |
authHeader interface{}
|
23 | 23 |
want want
|
24 | 24 |
}{
|
|
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}}},
|
25 | 27 |
{"Isn't valid without authHeader", "", want{nil, AuthError{realm}}},
|
26 | 28 |
{"Isn't valid for wrong user", makeAuthString("wrong-user", requiredPassword), want{nil, AuthError{realm}}},
|
27 | 29 |
{"Isn't valid for wrong password", makeAuthString(requiredUser, "wrong-password"), want{nil, AuthError{realm}}},
|