auth_basic.go 913 B

123456789101112131415161718192021222324252627282930313233
  1. package upstreamproxy
  2. import (
  3. "encoding/base64"
  4. "errors"
  5. "net/http"
  6. )
  7. type BasicHttpAuthState int
  8. const (
  9. BASIC_HTTP_AUTH_STATE_CHALLENGE_RECEIVED BasicHttpAuthState = iota
  10. BASIC_HTTP_AUTH_STATE_RESPONSE_GENERATED
  11. )
  12. type BasicHttpAuthenticator struct {
  13. state BasicHttpAuthState
  14. }
  15. func newBasicAuthenticator() *BasicHttpAuthenticator {
  16. return &BasicHttpAuthenticator{state: BASIC_HTTP_AUTH_STATE_CHALLENGE_RECEIVED}
  17. }
  18. func (a *BasicHttpAuthenticator) authenticate(req *http.Request, resp *http.Response, username, password string) error {
  19. if a.state == BASIC_HTTP_AUTH_STATE_CHALLENGE_RECEIVED {
  20. auth := username + ":" + password
  21. req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
  22. a.state = BASIC_HTTP_AUTH_STATE_RESPONSE_GENERATED
  23. return nil
  24. } else {
  25. return errors.New("upstreamproxy: Authorization is not accepted by the proxy server")
  26. }
  27. }