-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic_auth.go
46 lines (37 loc) · 1.32 KB
/
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 main
import (
"crypto/sha256"
"crypto/subtle"
"flag"
"net/http"
)
var basicHTTPAuthEnabled = flag.Bool("basicHTTPAuth", false, "Enable basic HTTP Authentication")
var basicUser = flag.String("basicHTTPUser", "admin", "username for basic http auth")
var basicPass = flag.String("basicHTTPPass", "password", "password for basic http auth")
// middleware to enfore User and Pass through basic HTTP authentication
type basicHTTPAuth struct {
User string
Pass string
Next http.Handler
}
func (a *basicHTTPAuth) Handler(next http.Handler) http.Handler {
a.Next = next
return a
}
func (a *basicHTTPAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if ok {
usernameHash := sha256.Sum256([]byte(username))
passwordHash := sha256.Sum256([]byte(password))
expectedUsernameHash := sha256.Sum256([]byte(a.User))
expectedPasswordHash := sha256.Sum256([]byte(a.Pass))
usernameMatch := (subtle.ConstantTimeCompare(usernameHash[:], expectedUsernameHash[:]) == 1)
passwordMatch := (subtle.ConstantTimeCompare(passwordHash[:], expectedPasswordHash[:]) == 1)
if usernameMatch && passwordMatch {
a.Next.ServeHTTP(w, r)
return
}
}
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}