-
Notifications
You must be signed in to change notification settings - Fork 0
/
basicauth.go
55 lines (44 loc) · 1.43 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
51
52
53
54
55
package http_transport
import (
"crypto/sha256"
"crypto/subtle"
"fmt"
"net/http"
)
type BasicAuthConfig struct {
Enabled bool `default:"false" usage:"allows to enable basic auth"`
Username string `usage:"auth username"`
Password string `usage:"auth password"`
}
func BasicAuthHandler(next http.Handler, cfg BasicAuthConfig) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := checkBasicAuth(r, cfg); err != nil {
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
http.Error(w, "Unauthorized: "+err.Error(), http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func checkBasicAuth(r *http.Request, cfg BasicAuthConfig) error {
if !cfg.Enabled {
return nil
}
username, password, ok := r.BasicAuth()
if !ok {
return fmt.Errorf("expected basic auth")
}
if username == "" || password == "" {
return fmt.Errorf("empty username or password")
}
userEncoded := sha256.Sum256([]byte(username))
passEncoded := sha256.Sum256([]byte(password))
expectedUserEncoded := sha256.Sum256([]byte(cfg.Username))
expectedPassEncoded := sha256.Sum256([]byte(cfg.Password))
usernameMatch := (subtle.ConstantTimeCompare(userEncoded[:], expectedUserEncoded[:]) == 1)
passwordMatch := (subtle.ConstantTimeCompare(passEncoded[:], expectedPassEncoded[:]) == 1)
if usernameMatch && passwordMatch {
return nil
}
return fmt.Errorf("credentials mismatch")
}