traefik/vendor/github.com/vulcand/oxy/utils/auth.go

42 lines
1.1 KiB
Go
Raw Normal View History

2017-02-07 21:33:23 +00:00
package utils
import (
"encoding/base64"
"fmt"
"strings"
)
type BasicAuth struct {
Username string
Password string
}
func (ba *BasicAuth) String() string {
encoded := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", ba.Username, ba.Password)))
return fmt.Sprintf("Basic %s", encoded)
}
func ParseAuthHeader(header string) (*BasicAuth, error) {
values := strings.Fields(header)
if len(values) != 2 {
return nil, fmt.Errorf(fmt.Sprintf("Failed to parse header '%s'", header))
}
2017-11-22 17:20:03 +00:00
authType := strings.ToLower(values[0])
if authType != "basic" {
return nil, fmt.Errorf("Expected basic auth type, got '%s'", authType)
2017-02-07 21:33:23 +00:00
}
2017-11-22 17:20:03 +00:00
encodedString := values[1]
decodedString, err := base64.StdEncoding.DecodeString(encodedString)
2017-02-07 21:33:23 +00:00
if err != nil {
return nil, fmt.Errorf("Failed to parse header '%s', base64 failed: %s", header, err)
}
2017-11-22 17:20:03 +00:00
values = strings.SplitN(string(decodedString), ":", 2)
2017-02-07 21:33:23 +00:00
if len(values) != 2 {
return nil, fmt.Errorf("Failed to parse header '%s', expected separator ':'", header)
}
return &BasicAuth{Username: values[0], Password: values[1]}, nil
}