-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathclient.go
118 lines (100 loc) · 2.59 KB
/
client.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package hawk
import (
"errors"
"net/http"
"strconv"
)
type Client struct {
Credential *Credential
Option *Option
}
func NewClient(c *Credential, o *Option) *Client {
return &Client{
Credential: c,
Option: o,
}
}
// Header builds a value to be set in the Authorization header.
func (c *Client) Header(method, uri string) (string, error) {
if c.Option.Hash == "" && c.Option.Payload != "" && c.Option.ContentType != "" {
ph := &PayloadHash{
ContentType: c.Option.ContentType,
Payload: c.Option.Payload,
Alg: c.Credential.Alg,
}
c.Option.Hash = ph.String()
}
m := &Mac{
Type: Header,
Credential: c.Credential,
Uri: uri,
Method: method,
Option: c.Option,
}
mac, err := m.String()
if err != nil {
return "", err
}
header := "Hawk " +
`id="` + c.Credential.ID + `"` +
", " +
`ts="` + strconv.FormatInt(c.Option.TimeStamp, 10) + `"` +
", " +
`nonce="` + c.Option.Nonce + `"`
if c.Option.Hash != "" {
header = header + ", " + `hash="` + c.Option.Hash + `"`
}
if c.Option.Ext != "" {
header = header + ", " + `ext="` + c.Option.Ext + `"`
}
header = header + ", " + `mac="` + mac + `"`
if c.Option.App != "" {
header = header + ", " + `app="` + c.Option.App + `"`
if c.Option.Dlg != "" {
header = header + ", " + `dlg="` + c.Option.Dlg + `"`
}
}
return header, nil
}
// Authenticate authenticate the Hawk server response from the HTTP response.
// Successful case returns true.
func (c *Client) Authenticate(res *http.Response) (bool, error) {
artifacts := *c.Option
wah := res.Header.Get("WWW-Authenticate")
if wah != "" {
// TODO: validate WWW-Authenticate Header
}
sah := res.Header.Get("Server-Authorization")
serverAuthAttributes := parseHawkHeader(sah)
artifacts.Ext = serverAuthAttributes["ext"]
artifacts.Hash = serverAuthAttributes["hash"]
m := &Mac{
Type: Response,
Credential: c.Credential,
Uri: res.Request.URL.String(),
Method: res.Request.Method,
Option: &artifacts,
}
mac, err := m.String()
if err != nil {
return false, err
}
if mac != serverAuthAttributes["mac"] {
return false, errors.New("Bad response mac")
}
if c.Option.Payload == "" && c.Option.ContentType == "" {
return true, nil
}
if serverAuthAttributes["hash"] == "" {
return false, errors.New("Missing response hash attribute")
}
ph := &PayloadHash{
ContentType: res.Header.Get("Content-Type"),
Payload: c.Option.Payload,
Alg: c.Credential.Alg,
}
if ph.String() != serverAuthAttributes["hash"] {
return false, errors.New("Bad response payload mac")
}
return true, nil
}