You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

basic_auth.go 852B

123456789101112131415161718192021222324252627282930313233
  1. package middleware
  2. import (
  3. "crypto/subtle"
  4. "fmt"
  5. "net/http"
  6. )
  7. // BasicAuth implements a simple middleware handler for adding basic http auth to a route.
  8. func BasicAuth(realm string, creds map[string]string) func(next http.Handler) http.Handler {
  9. return func(next http.Handler) http.Handler {
  10. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  11. user, pass, ok := r.BasicAuth()
  12. if !ok {
  13. basicAuthFailed(w, realm)
  14. return
  15. }
  16. credPass, credUserOk := creds[user]
  17. if !credUserOk || subtle.ConstantTimeCompare([]byte(pass), []byte(credPass)) != 1 {
  18. basicAuthFailed(w, realm)
  19. return
  20. }
  21. next.ServeHTTP(w, r)
  22. })
  23. }
  24. }
  25. func basicAuthFailed(w http.ResponseWriter, realm string) {
  26. w.Header().Add("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm))
  27. w.WriteHeader(http.StatusUnauthorized)
  28. }