auth_basic.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. username string
  33. password string
  34. }
  35. func newBasicAuthenticator(username, password string) *BasicHttpAuthenticator {
  36. return &BasicHttpAuthenticator{
  37. state: BASIC_HTTP_AUTH_STATE_CHALLENGE_RECEIVED,
  38. username: username,
  39. password: password,
  40. }
  41. }
  42. func (a *BasicHttpAuthenticator) Authenticate(req *http.Request, resp *http.Response) error {
  43. if a.state == BASIC_HTTP_AUTH_STATE_CHALLENGE_RECEIVED {
  44. a.state = BASIC_HTTP_AUTH_STATE_RESPONSE_GENERATED
  45. return a.PreAuthenticate(req)
  46. }
  47. return proxyError(fmt.Errorf("authorization is not accepted by the proxy server"))
  48. }
  49. func (a *BasicHttpAuthenticator) IsConnectionBased() bool {
  50. return false
  51. }
  52. func (a *BasicHttpAuthenticator) IsComplete() bool {
  53. return a.state == BASIC_HTTP_AUTH_STATE_RESPONSE_GENERATED
  54. }
  55. func (a *BasicHttpAuthenticator) Reset() {
  56. a.state = BASIC_HTTP_AUTH_STATE_CHALLENGE_RECEIVED
  57. }
  58. func (a *BasicHttpAuthenticator) PreAuthenticate(req *http.Request) error {
  59. auth := a.username + ":" + a.password
  60. req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
  61. return nil
  62. }