auth_basic.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package upstreamproxy
  20. import (
  21. "encoding/base64"
  22. "fmt"
  23. "net/http"
  24. )
  25. type BasicHttpAuthState int
  26. const (
  27. BASIC_HTTP_AUTH_STATE_CHALLENGE_RECEIVED BasicHttpAuthState = iota
  28. BASIC_HTTP_AUTH_STATE_RESPONSE_GENERATED
  29. )
  30. type BasicHttpAuthenticator struct {
  31. state BasicHttpAuthState
  32. }
  33. func newBasicAuthenticator() *BasicHttpAuthenticator {
  34. return &BasicHttpAuthenticator{state: BASIC_HTTP_AUTH_STATE_CHALLENGE_RECEIVED}
  35. }
  36. func (a *BasicHttpAuthenticator) Authenticate(req *http.Request, resp *http.Response, username, password string) error {
  37. if a.state == BASIC_HTTP_AUTH_STATE_CHALLENGE_RECEIVED {
  38. auth := username + ":" + password
  39. req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
  40. a.state = BASIC_HTTP_AUTH_STATE_RESPONSE_GENERATED
  41. return nil
  42. } else {
  43. return proxyError(fmt.Errorf("Authorization is not accepted by the proxy server"))
  44. }
  45. }