-
Notifications
You must be signed in to change notification settings - Fork 15
/
signer.go
79 lines (62 loc) · 1.81 KB
/
signer.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
package httpsignatures
import (
"net/http"
"strings"
"time"
)
// Signer is used to create a signature for a given request.
type Signer struct {
algorithm *Algorithm
headers HeaderList
}
var (
// DefaultSha1Signer will sign requests with the url and date using the SHA1 algorithm.
// Users are encouraged to create their own signer with the headers they require.
DefaultSha1Signer = NewSigner(AlgorithmHmacSha1, RequestTarget, "date")
// DefaultSha256Signer will sign requests with the url and date using the SHA256 algorithm.
// Users are encouraged to create their own signer with the headers they require.
DefaultSha256Signer = NewSigner(AlgorithmHmacSha256, RequestTarget, "date")
)
func NewSigner(algorithm *Algorithm, headers ...string) *Signer {
hl := HeaderList{}
for _, header := range headers {
hl = append(hl, strings.ToLower(header))
}
return &Signer{
algorithm: algorithm,
headers: hl,
}
}
// SignRequest adds a http signature to the Signature: HTTP Header
func (s Signer) SignRequest(id, key string, r *http.Request) error {
sig, err := s.buildSignature(id, key, r)
if err != nil {
return err
}
r.Header.Add(headerSignature, sig.String())
return nil
}
// AuthRequest adds a http signature to the Authorization: HTTP Header
func (s Signer) AuthRequest(id, key string, r *http.Request) error {
sig, err := s.buildSignature(id, key, r)
if err != nil {
return err
}
r.Header.Add(headerAuthorization, authScheme+sig.String())
return nil
}
func (s Signer) buildSignature(id, key string, r *http.Request) (*Signature, error) {
if r.Header.Get("date") == "" {
r.Header.Set("date", time.Now().Format(time.RFC1123))
}
sig := &Signature{
KeyID: id,
Algorithm: s.algorithm,
Headers: s.headers,
}
err := sig.sign(key, r)
if err != nil {
return nil, err
}
return sig, nil
}