forked from cloudfoundry/gorouter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic_auth.go
46 lines (38 loc) · 932 Bytes
/
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
package http
import (
"encoding/base64"
"fmt"
"net/http"
"strings"
)
type Authenticator func(user, password string) bool
type BasicAuth struct {
http.Handler
Authenticator
}
func extractCredentials(req *http.Request) []string {
x := strings.Split(req.Header.Get("Authorization"), " ")
if len(x) != 2 || x[0] != "Basic" {
return nil
}
y, err := base64.StdEncoding.DecodeString(x[1])
if err != nil {
return nil
}
z := strings.Split(string(y), ":")
if len(z) != 2 {
return nil
}
return z
}
func (x *BasicAuth) ServeHTTP(w http.ResponseWriter, req *http.Request) {
y := extractCredentials(req)
// Beware of the hack
if req.URL.Path != "/healthz" && (y == nil || !x.Authenticator(y[0], y[1])) {
w.Header().Set("WWW-Authenticate", "Basic")
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(fmt.Sprintf("%d Unauthorized\n", http.StatusUnauthorized)))
} else {
x.Handler.ServeHTTP(w, req)
}
}