-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproof.go
85 lines (72 loc) · 1.68 KB
/
proof.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
package dpop
import (
"net/http"
"net/url"
"time"
"gopkg.in/square/go-jose.v2"
"gopkg.in/square/go-jose.v2/jwt"
)
type Proof interface {
// ForRequest annotates an HTTP Request with a DPoP header.
ForRequest(r *http.Request, extraClaims interface{}) error
}
type proofer struct {
signingKey jose.SigningKey
signer jose.Signer
now func() time.Time
}
// New creates a DPoP Proof that can generate DPoP headers for a request.
func New(key jose.SigningKey) (Proof, error) {
signer, err := jose.NewSigner(key, &jose.SignerOptions{
EmbedJWK: true,
ExtraHeaders: map[jose.HeaderKey]interface{}{
jose.HeaderType: typDPOP,
},
})
if err != nil {
return nil, err
}
return &proofer{
signingKey: key,
signer: signer,
now: time.Now,
}, nil
}
const (
proofExp = time.Minute * 5
proofNbf = -2 * time.Minute
)
func mungedURL(input *url.URL) *url.URL {
rv := new(url.URL)
*rv = *input
rv.Fragment = ""
rv.RawQuery = ""
rv.ForceQuery = false
return rv
}
func (p *proofer) ForRequest(r *http.Request, extraClaims interface{}) error {
builder := jwt.Signed(p.signer)
now := p.now()
exp := now.Add(proofExp)
jti := randCryptoString(16)
claims := &jwt.Claims{
ID: jti,
NotBefore: jwt.NewNumericDate(now.Add(proofNbf)),
Expiry: jwt.NewNumericDate(exp),
IssuedAt: jwt.NewNumericDate(now),
}
builder = builder.Claims(claims)
builder = builder.Claims(map[string]interface{}{
claimHTTPMethod: r.Method,
claimHTTPURL: mungedURL(r.URL).String(),
})
if extraClaims != nil {
builder = builder.Claims(extraClaims)
}
token, err := builder.CompactSerialize()
if err != nil {
return err
}
r.Header.Set(httpHeader, token)
return nil
}