BasicAuth parses the Authorization header on req If absent or invalid, an error is returned.
(req *http.Request)
| 81 | // BasicAuth parses the Authorization header on req |
| 82 | // If absent or invalid, an error is returned. |
| 83 | func BasicAuth(req *http.Request) (username, password string, err error) { |
| 84 | auth := req.Header.Get("Authorization") |
| 85 | if auth == "" { |
| 86 | err = fmt.Errorf("Missing \"Authorization\" in header") |
| 87 | return |
| 88 | } |
| 89 | matches := basicAuthPattern.FindStringSubmatch(auth) |
| 90 | if len(matches) != 2 { |
| 91 | err = fmt.Errorf("Bogus Authorization header") |
| 92 | return |
| 93 | } |
| 94 | encoded := matches[1] |
| 95 | enc := base64.StdEncoding |
| 96 | decBuf := make([]byte, enc.DecodedLen(len(encoded))) |
| 97 | n, err := enc.Decode(decBuf, []byte(encoded)) |
| 98 | if err != nil { |
| 99 | return |
| 100 | } |
| 101 | pieces := strings.SplitN(string(decBuf[0:n]), ":", 2) |
| 102 | if len(pieces) != 2 { |
| 103 | err = fmt.Errorf("didn't get two pieces") |
| 104 | return |
| 105 | } |
| 106 | return pieces[0], pieces[1], nil |
| 107 | } |