auth_basic.go 919 B

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