-
Notifications
You must be signed in to change notification settings - Fork 4
/
basicauth.go
50 lines (44 loc) · 1.44 KB
/
basicauth.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
package basicauth
import (
"crypto/subtle"
"fmt"
"net/http"
)
// New returns a piece of middleware that will allow access only
// if the provided credentials match within the given service
// otherwise it will return a 401 and not call the next handler.
func New(realm string, credentials map[string][]string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if !ok {
unauthorized(w, realm)
return
}
validPasswords, userFound := credentials[username]
if !userFound {
unauthorized(w, realm)
return
}
for _, validPassword := range validPasswords {
validPasswordBytes := []byte(validPassword)
passwordBytes := []byte(password)
// take the same amount of time if the lengths are different
// this is required since ConstantTimeCompare returns immediately when slices of different length are compared
if len(password) != len(validPassword) {
subtle.ConstantTimeCompare(validPasswordBytes, validPasswordBytes)
} else {
if subtle.ConstantTimeCompare(passwordBytes, validPasswordBytes) == 1 {
next.ServeHTTP(w, r)
return
}
}
}
unauthorized(w, realm)
})
}
}
func unauthorized(w http.ResponseWriter, realm string) {
w.Header().Add("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm))
w.WriteHeader(http.StatusUnauthorized)
}