basicAuth.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package dynamicproxy
  2. import (
  3. "errors"
  4. "net/http"
  5. "strings"
  6. "imuslab.com/zoraxy/mod/auth"
  7. )
  8. /*
  9. BasicAuth.go
  10. This file handles the basic auth on proxy endpoints
  11. if RequireBasicAuth is set to true
  12. */
  13. func (h *ProxyHandler) handleBasicAuthRouting(w http.ResponseWriter, r *http.Request, pe *ProxyEndpoint) error {
  14. if len(pe.BasicAuthExceptionRules) > 0 {
  15. //Check if the current path matches the exception rules
  16. for _, exceptionRule := range pe.BasicAuthExceptionRules {
  17. if strings.HasPrefix(r.RequestURI, exceptionRule.PathPrefix) {
  18. //This path is excluded from basic auth
  19. return nil
  20. }
  21. }
  22. }
  23. u, p, ok := r.BasicAuth()
  24. if !ok {
  25. w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  26. w.WriteHeader(401)
  27. return errors.New("unauthorized")
  28. }
  29. //Check for the credentials to see if there is one matching
  30. hashedPassword := auth.Hash(p)
  31. matchingFound := false
  32. for _, cred := range pe.BasicAuthCredentials {
  33. if u == cred.Username && hashedPassword == cred.PasswordHash {
  34. matchingFound = true
  35. break
  36. }
  37. }
  38. if !matchingFound {
  39. h.logRequest(r, false, 401, "host", pe.Domain)
  40. w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  41. w.WriteHeader(401)
  42. return errors.New("unauthorized")
  43. }
  44. return nil
  45. }