authelia.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package dynamicproxy
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. )
  8. func (h *ProxyHandler) handleAutheliaAuthRouting(w http.ResponseWriter, r *http.Request, pe *ProxyEndpoint) error {
  9. err := handleAutheliaAuth(w, r, pe)
  10. if err != nil {
  11. h.Parent.logRequest(r, false, 401, "host", r.URL.Hostname())
  12. }
  13. return err
  14. }
  15. func handleAutheliaAuth(w http.ResponseWriter, r *http.Request, pe *ProxyEndpoint) error {
  16. client := &http.Client{}
  17. // TODO: provide authelia url by config variable
  18. req, err := http.NewRequest("POST", "https://authelia.mydomain.com/api/verify", nil)
  19. if err != nil {
  20. pe.parent.Option.Logger.PrintAndLog("Authelia", "Unable to create request", err)
  21. w.WriteHeader(401)
  22. return errors.New("unauthorized")
  23. }
  24. scheme := "http"
  25. if r.TLS != nil {
  26. scheme = "https"
  27. }
  28. req.Header.Add("X-Original-URL", fmt.Sprintf("%s://%s", scheme, r.Host))
  29. // Copy cookies from the incoming request
  30. for _, cookie := range r.Cookies() {
  31. req.AddCookie(cookie)
  32. }
  33. resp, err := client.Do(req)
  34. if err != nil {
  35. pe.parent.Option.Logger.PrintAndLog("Authelia", "Unable to verify", err)
  36. w.WriteHeader(401)
  37. return errors.New("unauthorized")
  38. }
  39. if resp.StatusCode != 200 {
  40. // TODO: provide authelia url by config variable
  41. redirectURL := "https://authelia.mydomain.com/?rd=" + url.QueryEscape(scheme+"://"+r.Host+r.URL.String()) + "&rm=" + r.Method
  42. http.Redirect(w, r, redirectURL, http.StatusSeeOther)
  43. return errors.New("unauthorized")
  44. }
  45. return nil
  46. }