-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic.go
38 lines (35 loc) · 972 Bytes
/
basic.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package oauth
import (
"encoding/base64"
"errors"
"net/http"
"strings"
)
// GetBasicAuthentication get username and password from Authorization header
func GetBasicAuthentication(r *http.Request) (username, password string, err error) {
if header := r.Header.Get("Authorization"); header != "" {
if strings.ToLower(header[:6]) == "basic " {
// decode header value
value, err := base64.StdEncoding.DecodeString(header[6:])
if err != nil {
return "", "", err
}
strValue := string(value)
if ind := strings.Index(strValue, ":"); ind > 0 {
return strValue[:ind], strValue[ind+1:], nil
}
}
}
return "", "", nil
}
// Check Basic Authorization header credentials
func CheckBasicAuthentication(username, password string, r *http.Request) error {
u, p, err := GetBasicAuthentication(r)
if err != nil {
return err
}
if u != "" && p != "" && u != username && p != password {
return errors.New("invalid credentials")
}
return nil
}