Skip to content

Instantly share code, notes, and snippets.

@taylortrimble
Created August 16, 2014 21:34
Show Gist options
  • Save taylortrimble/7a31251f1141bbebcb32 to your computer and use it in GitHub Desktop.
Save taylortrimble/7a31251f1141bbebcb32 to your computer and use it in GitHub Desktop.
Get Basic Auth username and password in Go
// GetBasicAuth parses the username and password from an HTTP request Basic Authorization header.
// See RFC 2617.
func GetBasicAuth(r *http.Request) (username, password string, err error) {
// Get the Authorization header.
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
return "", "", errors.New("authorization header was not provided")
}
// Check the Authorization type is "Basic"
authComponents := strings.Split(authHeader, " ")
if len(authComponents) != 2 {
return "", "", errors.New("authorization header is poorly formatted")
}
if authComponents[0] != "Basic" {
return "", "", errors.New("authorization type Basic was expected")
}
// Base64 Decode the user-pass string.
decoded, err := base64.StdEncoding.DecodeString(authComponents[1])
if err != nil {
return "", "", err
}
// Split apart the username and password.
userPassComponents := strings.Split(string(decoded), ":")
if len(userPassComponents) != 2 {
return "", "", errors.New("authorization header is poorly formatted")
}
username = userPassComponents[0]
password = userPassComponents[1]
return username, password, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment