-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathmw_upstream_basic_auth.go
71 lines (56 loc) · 2.07 KB
/
mw_upstream_basic_auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package gateway
import (
"fmt"
"net/http"
"github.com/sirupsen/logrus"
"github.com/TykTechnologies/tyk/header"
"github.com/TykTechnologies/tyk/internal/httputil"
)
// UpstreamBasicAuth is a middleware that will do basic authentication for upstream connections.
// UpstreamBasicAuth middleware is only supported in Tyk OAS API definitions.
type UpstreamBasicAuth struct {
*BaseMiddleware
}
// Name returns the name of middleware.
func (t *UpstreamBasicAuth) Name() string {
return "UpstreamBasicAuth"
}
// EnabledForSpec returns true if the middleware is enabled based on API Spec.
func (t *UpstreamBasicAuth) EnabledForSpec() bool {
if !t.Spec.UpstreamAuth.Enabled {
return false
}
if !t.Spec.UpstreamAuth.BasicAuth.Enabled {
return false
}
return true
}
// ProcessRequest will inject basic auth info into request context so that it can be used during reverse proxy.
func (t *UpstreamBasicAuth) ProcessRequest(_ http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {
basicAuthConfig := t.Spec.UpstreamAuth.BasicAuth
upstreamBasicAuthProvider := UpstreamBasicAuthProvider{
HeaderName: header.Authorization,
}
if basicAuthConfig.HeaderName != "" {
upstreamBasicAuthProvider.HeaderName = basicAuthConfig.HeaderName
}
upstreamBasicAuthProvider.AuthValue = httputil.AuthHeader(basicAuthConfig.Username, basicAuthConfig.Password)
httputil.SetUpstreamAuth(r, upstreamBasicAuthProvider)
return nil, http.StatusOK
}
// UpstreamBasicAuthProvider implements upstream auth provider.
type UpstreamBasicAuthProvider struct {
// HeaderName is the header name to be used to fill upstream auth with.
HeaderName string
// AuthValue is the value of auth header.
AuthValue string
}
// Fill sets the request's HeaderName with AuthValue
func (u UpstreamBasicAuthProvider) Fill(r *http.Request) {
if r.Header.Get(u.HeaderName) != "" {
log.WithFields(logrus.Fields{
"header": u.HeaderName,
}).Warn(fmt.Sprintf("%s header conflict detected: client header overwritten by Gateway upstream authentication header", u.HeaderName))
}
r.Header.Set(u.HeaderName, u.AuthValue)
}