1
0
mirror of https://github.com/golang/go synced 2024-11-24 22:57:57 -07:00

net/http: add support for proxy basic authentication

Add functions to support getting and setting proxy basic authentication.
This commit is contained in:
Yuval Shalev 2022-09-18 13:32:17 +03:00
parent 63d05642d4
commit 0708e33c4c
2 changed files with 35 additions and 0 deletions

View File

@ -951,6 +951,17 @@ func (r *Request) BasicAuth() (username, password string, ok bool) {
return parseBasicAuth(auth)
}
// ProxyBasicAuth returns the username and password provided in the request's
// Proxy-Authorization header, if the request uses HTTP Basic Authentication.
// See RFC 2068, Section 14.
func (r *Request) ProxyBasicAuth() (username, password string, ok bool) {
auth := r.Header.Get("Proxy-Authorization")
if auth == "" {
return "", "", false
}
return parseBasicAuth(auth)
}
// parseBasicAuth parses an HTTP Basic Authentication string.
// "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
func parseBasicAuth(auth string) (username, password string, ok bool) {
@ -986,6 +997,10 @@ func (r *Request) SetBasicAuth(username, password string) {
r.Header.Set("Authorization", "Basic "+basicAuth(username, password))
}
func (r *Request) SetProxyBasicAuth(username, password string) {
r.Header.Set("Proxy-Authorization", "Basic "+basicAuth(username, password))
}
// parseRequestLine parses "GET /foo HTTP/1.1" into its three parts.
func parseRequestLine(line string) (method, requestURI, proto string, ok bool) {
method, rest, ok1 := strings.Cut(line, " ")

View File

@ -366,6 +366,14 @@ func TestSetBasicAuth(t *testing.T) {
}
}
func TestSetProxyBasicAuth(t *testing.T) {
r, _ := NewRequest("GET", "http://example.com/", nil)
r.SetProxyBasicAuth("Aladdin", "open sesame")
if g, e := r.Header.Get("Proxy-Authorization"), "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="; g != e {
t.Errorf("got header %q, want %q", g, e)
}
}
func TestMultipartRequest(t *testing.T) {
// Test that we can read the values and files of a
// multipart request with FormValue and FormFile,
@ -744,6 +752,18 @@ func TestParseBasicAuth(t *testing.T) {
}
}
func TestParseProxyBasicAuth(t *testing.T) {
for _, tt := range parseBasicAuthTests {
r, _ := NewRequest("GET", "http://example.com/", nil)
r.Header.Set("Proxy-Authorization", tt.header)
username, password, ok := r.ProxyBasicAuth()
if ok != tt.ok || username != tt.username || password != tt.password {
t.Errorf("BasicAuth() = %#v, want %#v", getBasicAuthTest{username, password, ok},
getBasicAuthTest{tt.username, tt.password, tt.ok})
}
}
}
type logWrites struct {
t *testing.T
dst *[]string