basic.go 672 B

12345678910111213141516171819202122232425262728293031
  1. package authutil
  2. import (
  3. "encoding/base64"
  4. "net/http"
  5. "strings"
  6. )
  7. // DecodeBasic extracts username and password from given header using HTTP Basic Auth.
  8. // It returns empty strings if values are not presented or not valid.
  9. func DecodeBasic(header http.Header) (username, password string) {
  10. if len(header) == 0 {
  11. return "", ""
  12. }
  13. fields := strings.Fields(header.Get("Authorization"))
  14. if len(fields) != 2 || fields[0] != "Basic" {
  15. return "", ""
  16. }
  17. p, err := base64.StdEncoding.DecodeString(fields[1])
  18. if err != nil {
  19. return "", ""
  20. }
  21. creds := strings.SplitN(string(p), ":", 2)
  22. if len(creds) == 1 {
  23. return creds[0], ""
  24. }
  25. return creds[0], creds[1]
  26. }