-
Notifications
You must be signed in to change notification settings - Fork 0
/
payload.go
82 lines (68 loc) · 1.82 KB
/
payload.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
package jwt
import (
"bytes"
"crypto/ed25519"
"encoding/base64"
"encoding/json"
"errors"
)
type Payload struct {
PrivateKey ed25519.PrivateKey `json:"-"`
PublicKey ed25519.PublicKey `json:"-"`
Validator []Validator `json:"-"`
Issuer string `json:"iss,omitempty"`
Subject string `json:"sub,omitempty"`
Audience Audience `json:"aud,omitempty"`
ExpirationTime *Time `json:"exp,omitempty"`
NotBefore *Time `json:"nbf,omitempty"`
IssuedAt *Time `json:"iat,omitempty"`
JWTID string `json:"jti,omitempty"`
}
func (p Payload) MarshalJSON() ([]byte, error) {
type T Payload
j, err := json.Marshal(struct{ T }{T: (T)(p)})
if err != nil {
return nil, err
}
enc := base64.RawURLEncoding
p6l := enc.EncodedLen(len(j))
s6l := enc.EncodedLen(ed25519.SignatureSize)
t := make([]byte, 1+p6l+1+s6l+1)
t[0] = '"'
enc.Encode(t[1:], j)
t[1+p6l] = '.'
enc.Encode(t[1+p6l+1:], ed25519.Sign(p.PrivateKey, j)) // copy(t[1+p6l+1:], sig)
t[len(t)-1] = '"'
return t, nil
}
func (p *Payload) UnmarshalJSON(b []byte) error {
i := bytes.IndexByte(b, '.')
if i < 0 {
return errors.New("no .")
}
encoding := base64.RawURLEncoding
pl := make([]byte, encoding.DecodedLen(len(b[1:i])))
_, err := encoding.Decode(pl, b[1:i])
if err != nil {
return err
}
sig := make([]byte, encoding.DecodedLen(len(b[i+1:len(b)-1])))
_, err = encoding.Decode(sig, b[i+1:len(b)-1])
if err != nil {
return err
}
if !ed25519.Verify(p.PublicKey, pl, sig) {
return errors.New("invalid signiture")
}
type T Payload
t := struct{ *T }{T: (*T)(p)}
if err := json.Unmarshal(pl, &t); err != nil {
return err
}
for _, v := range p.Validator {
if err = v(*p); err != nil {
return err
}
}
return nil
}