basicAuth.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. err := handleBasicAuth(w, r, pe)
  15. if err != nil {
  16. h.Parent.logRequest(r, false, 401, "host", r.URL.Hostname())
  17. }
  18. return err
  19. }
  20. // Handle basic auth logic
  21. // do not write to http.ResponseWriter if err return is not nil (already handled by this function)
  22. func handleBasicAuth(w http.ResponseWriter, r *http.Request, pe *ProxyEndpoint) error {
  23. if len(pe.AuthenticationProvider.BasicAuthExceptionRules) > 0 {
  24. //Check if the current path matches the exception rules
  25. for _, exceptionRule := range pe.AuthenticationProvider.BasicAuthExceptionRules {
  26. if strings.HasPrefix(r.RequestURI, exceptionRule.PathPrefix) {
  27. //This path is excluded from basic auth
  28. return nil
  29. }
  30. }
  31. }
  32. u, p, ok := r.BasicAuth()
  33. if !ok {
  34. w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  35. w.WriteHeader(401)
  36. return errors.New("unauthorized")
  37. }
  38. //Check for the credentials to see if there is one matching
  39. hashedPassword := auth.Hash(p)
  40. matchingFound := false
  41. for _, cred := range pe.AuthenticationProvider.BasicAuthCredentials {
  42. if u == cred.Username && hashedPassword == cred.PasswordHash {
  43. matchingFound = true
  44. //Set the X-Remote-User header
  45. r.Header.Set("X-Remote-User", u)
  46. break
  47. }
  48. }
  49. if !matchingFound {
  50. w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  51. w.WriteHeader(401)
  52. return errors.New("unauthorized")
  53. }
  54. return nil
  55. }