-
Notifications
You must be signed in to change notification settings - Fork 16
/
hawk_support.go
89 lines (78 loc) · 2.13 KB
/
hawk_support.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
package hawksupport
import (
"io"
"log"
"net/http"
"time"
"github.com/hiyosi/hawk"
)
type HTTPClient interface {
Get(url string) (resp *http.Response, err error)
Do(req *http.Request) (*http.Response, error)
}
type credentialStore struct {
key string
}
func NewCredentialStore(key string) hawk.CredentialStore {
return &credentialStore{key}
}
func (c *credentialStore) GetCredential(id string) (*hawk.Credential, error) {
return &hawk.Credential{
ID: id,
Key: c.key,
Alg: hawk.SHA256,
}, nil
}
func HawkMiddleware(next http.HandlerFunc, credentialStore hawk.CredentialStore, hostPort string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
s := hawk.NewServer(credentialStore)
s.AuthOption = &hawk.AuthOption{
CustomHostPort: hostPort,
}
if r.Header.Get("Authorization") == "" {
log.Println("Request missing authorization header")
w.Header().Set("www-authenticate", "hawk")
w.WriteHeader(http.StatusUnauthorized)
return
}
cred, err := s.Authenticate(r)
if err != nil {
log.Printf("HAWK authentication failed: %s", err.Error())
w.Header().Set("www-authenticate", "hawk")
w.WriteHeader(http.StatusUnauthorized)
return
}
opt := &hawk.Option{
TimeStamp: time.Now().Unix(),
}
h, _ := s.Header(r, cred, opt)
w.Header().Set("server-authorization", h)
next(w, r)
}
}
func HawkGet(client HTTPClient, id string, key string, url string) (*http.Response, error) {
req, _ := http.NewRequest("GET", url, nil)
authorize(req, id, key, url, "GET")
return client.Do(req)
}
func HawkPost(client HTTPClient, id string, key string, url string, body io.Reader) (*http.Response, error) {
req, _ := http.NewRequest("POST", url, body)
req.Header.Set("Content-Type", "application/json")
authorize(req, id, key, url, "POST")
return client.Do(req)
}
func authorize(req *http.Request, id string, key string, url string, method string) {
c := hawk.NewClient(
&hawk.Credential{
ID: id,
Key: key,
Alg: hawk.SHA256,
},
&hawk.Option{
TimeStamp: time.Now().Unix(),
Nonce: "nonce",
},
)
header, _ := c.Header(method, url)
req.Header.Set("authorization", header)
}