Merge pull request #2558 from kelseyhightower/add-basic-auth

netutil: add BasicAuth function
release-2.1
Kelsey Hightower 2015-03-20 22:34:06 -07:00
commit 454b66edde
2 changed files with 39 additions and 2 deletions

View File

@ -24,6 +24,7 @@ import (
"github.com/coreos/etcd/etcdserver" "github.com/coreos/etcd/etcdserver"
"github.com/coreos/etcd/etcdserver/etcdhttp/httptypes" "github.com/coreos/etcd/etcdserver/etcdhttp/httptypes"
"github.com/coreos/etcd/etcdserver/security" "github.com/coreos/etcd/etcdserver/security"
"github.com/coreos/etcd/pkg/netutil"
) )
type securityHandler struct { type securityHandler struct {
@ -46,7 +47,7 @@ func hasRootAccess(sec *security.Store, r *http.Request) bool {
if !sec.SecurityEnabled() { if !sec.SecurityEnabled() {
return true return true
} }
username, password, ok := r.BasicAuth() username, password, ok := netutil.BasicAuth(r)
if !ok { if !ok {
return false return false
} }
@ -73,7 +74,7 @@ func hasKeyPrefixAccess(sec *security.Store, r *http.Request, key string) bool {
if !sec.SecurityEnabled() { if !sec.SecurityEnabled() {
return true return true
} }
username, password, ok := r.BasicAuth() username, password, ok := netutil.BasicAuth(r)
if !ok { if !ok {
return false return false
} }

View File

@ -15,10 +15,13 @@
package netutil package netutil
import ( import (
"encoding/base64"
"log" "log"
"net" "net"
"net/http"
"net/url" "net/url"
"reflect" "reflect"
"strings"
) )
var ( var (
@ -99,3 +102,36 @@ func URLStringsEqual(a []string, b []string) bool {
return URLsEqual(urlsA, urlsB) return URLsEqual(urlsA, urlsB)
} }
// BasicAuth returns the username and password provided in the request's
// Authorization header, if the request uses HTTP Basic Authentication.
// See RFC 2617, Section 2.
// Based on the BasicAuth method from the Golang standard lib.
// TODO: use the standard lib BasicAuth method when we move to Go 1.4.
func BasicAuth(r *http.Request) (username, password string, ok bool) {
auth := r.Header.Get("Authorization")
if auth == "" {
return
}
return parseBasicAuth(auth)
}
// parseBasicAuth parses an HTTP Basic Authentication string.
// "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
// Taken from the Golang standard lib.
// TODO: use the standard lib BasicAuth method when we move to Go 1.4.
func parseBasicAuth(auth string) (username, password string, ok bool) {
if !strings.HasPrefix(auth, "Basic ") {
return
}
c, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(auth, "Basic "))
if err != nil {
return
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return
}
return cs[:s], cs[s+1:], true
}