|
@@ -0,0 +1,48 @@
|
|
|
+package main
|
|
|
+
|
|
|
+import (
|
|
|
+ "crypto/sha256"
|
|
|
+ "crypto/subtle"
|
|
|
+ "net/http"
|
|
|
+)
|
|
|
+
|
|
|
+func basicAuth(next http.HandlerFunc) http.HandlerFunc {
|
|
|
+ return http.HandlerFunc(func(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("your expected username"))
|
|
|
+ expectedPasswordHash := sha256.Sum256([]byte("your expected password"))
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ usernameMatch := 1 == subtle.ConstantTimeCompare(usernameHash[:], expectedUsernameHash[:])
|
|
|
+ passwordMatch := 1 == subtle.ConstantTimeCompare(passwordHash[:], expectedPasswordHash[:])
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ if usernameMatch && passwordMatch {
|
|
|
+ next.ServeHTTP(w, r)
|
|
|
+ return
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
|
|
|
+ http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
|
|
|
+ })
|
|
|
+}
|