forked from BTBurke/caddy-extauth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extauth.go
98 lines (87 loc) · 2.21 KB
/
extauth.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package extauth
import (
"crypto/tls"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
func (a *Auth) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
// Before anything else, see if we need to check this request and short circuit if not.
if len(a.Prefixes) != 0 {
skipAuthorization := true
for _, prefix := range a.Prefixes {
if strings.HasPrefix(r.URL.Path, prefix) {
skipAuthorization = false
break
}
}
if skipAuthorization {
return a.Next.ServeHTTP(w, r)
}
}
// create client if it doesn't exist, in normal operation client should be nil
// but having the client as part of the auth struct is useful for testing
if a.client == nil {
a.client = &http.Client{}
}
a.client.Timeout = a.Timeout
url, err := url.Parse(a.Proxy)
if err != nil {
return handleUnathorized(w, nil), nil
}
if url.Scheme == "https" && a.InsecureSkipVerify {
a.client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
req, err := http.NewRequest("GET", url.String(), nil)
if err != nil {
return handleUnathorized(w, nil), nil
}
// in router mode, deep copy the URL parameters to the auth request
if a.Router {
deepCopyURL(r, req)
}
if a.Cookies {
for _, c := range r.Cookies() {
req.AddCookie(c)
}
}
if a.Headers {
req.Header = r.Header
// Retain original host header
req.Host = r.Host
req.Header.Add("X-Auth-URL", r.URL.String())
}
resp, err := a.client.Do(req)
if err != nil {
return handleUnathorized(w, nil), nil
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
for _, c := range resp.Cookies() {
r.AddCookie(c)
}
r.Header = resp.Header
return a.Next.ServeHTTP(w, r)
}
respReason, err := ioutil.ReadAll(resp.Body)
if err != nil {
return handleUnathorized(w, nil), nil
}
return handleUnathorized(w, respReason), nil
}
func handleUnathorized(w http.ResponseWriter, resp []byte) int {
w.WriteHeader(http.StatusUnauthorized)
w.Write(resp)
return 0
}
func deepCopyURL(from, to *http.Request) {
to.URL.User = from.URL.User
to.URL.Path = from.URL.Path
to.URL.RawPath = from.URL.Path
to.URL.ForceQuery = from.URL.ForceQuery
to.URL.RawQuery = from.URL.RawQuery
to.URL.Fragment = from.URL.Fragment
}