forked from openshift/osin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
69 lines (60 loc) · 1.57 KB
/
util.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package osin
import (
"encoding/base64"
"errors"
"net/http"
"strings"
)
// Parse basic authentication header
type BasicAuth struct {
Username string
Password string
}
// Return authorization header data
func CheckBasicAuth(r *http.Request) (*BasicAuth, error) {
if r.Header.Get("Authorization") == "" {
return nil, nil
}
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(s) != 2 || s[0] != "Basic" {
return nil, errors.New("Invalid authorization header")
}
b, err := base64.StdEncoding.DecodeString(s[1])
if err != nil {
return nil, err
}
pair := strings.SplitN(string(b), ":", 2)
if len(pair) != 2 {
return nil, errors.New("Invalid authorization message")
}
return &BasicAuth{Username: pair[0], Password: pair[1]}, nil
}
// getClientAuth checks client basic authentication in params if allowed,
// otherwise gets it from the header.
// Sets an error on the response if no auth is present or a server error occurs.
func getClientAuth(w *Response, r *http.Request, allowQueryParams bool) *BasicAuth {
if allowQueryParams {
// Allow for auth without password
if _, hasSecret := r.Form["client_secret"]; hasSecret {
auth := &BasicAuth{
Username: r.Form.Get("client_id"),
Password: r.Form.Get("client_secret"),
}
if auth.Username != "" {
return auth
}
}
}
auth, err := CheckBasicAuth(r)
if err != nil {
w.SetError(E_INVALID_REQUEST, "")
w.InternalError = err
return nil
}
if auth == nil {
w.SetError(E_INVALID_REQUEST, "")
w.InternalError = errors.New("Client authentication not sent")
return nil
}
return auth
}