-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheader.go
112 lines (93 loc) · 2.25 KB
/
header.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
package jwt
import (
"hash"
"crypto/sha256"
"crypto/sha512"
"strings"
"time"
)
type hasherFunc = func()(hash.Hash)
type SignType string
const (
SignHS512 SignType = "HS512"
SignHS384 SignType = "HS384"
SignHS512_256 SignType = "HS512/256"
SignHS512_224 SignType = "HS512/224"
SignHS256 SignType = "HS256"
SignHS224 SignType = "HS224"
)
func (s SignType)Hasher()(hasherFunc){
switch (SignType)(strings.ToUpper((string)(s))) {
case SignHS512: return sha512.New
case SignHS384: return sha512.New384
case SignHS512_256: return sha512.New512_256
case SignHS512_224: return sha512.New512_224
case SignHS256: return sha256.New
case SignHS224: return sha256.New224
}
panic("Unknown signtype: " + (string)(s))
}
type Header struct{
NoChange string `json:"typ"`
Signer SignType `json:"alg"`
IssuedAt time.Time `json:"isa"`
Id string `json:"jti,omitempty"`
Expiration *time.Time `json:"exp,omitempty"`
NotBefore *time.Time `json:"nbf,omitempty"`
Issuer string `json:"iss,omitempty"`
Audience string `json:"aud,omitempty"`
Subject string `json:"sub,omitempty"`
Extra interface{} `json:"ext,omitempty"`
}
func NewHeader()(h *Header){
return &Header{
NoChange: "JWT",
Signer: SignHS256,
}
}
func (h *Header)SetSigner(s SignType)(*Header){
h.Signer = s
return h
}
func (h *Header)SetId(id string)(*Header){
h.Id = id
return h
}
func (h *Header)SetExpiration(t time.Time)(*Header){
h.Expiration = &t
return h
}
func (h *Header)IsExpired()(bool){
return h.Expiration != nil && h.Expiration.Before(time.Now())
}
func (h *Header)Duration(t time.Duration)(*Header){
h.SetExpiration(time.Now().Add(t))
return h
}
func (h *Header)SetNotBefore(t time.Time)(*Header){
h.NotBefore = &t
return h
}
func (h *Header)IsActivity()(bool){
return h.NotBefore == nil || h.NotBefore.After(time.Now())
}
func (h *Header)ActivateAfter(t time.Duration)(*Header){
h.SetNotBefore(time.Now().Add(t))
return h
}
func (h *Header)SetIssuer(v string)(*Header){
h.Issuer = v
return h
}
func (h *Header)SetAudience(v string)(*Header){
h.Audience = v
return h
}
func (h *Header)SetSubject(v string)(*Header){
h.Subject = v
return h
}
func (h *Header)SetExtra(v interface{})(*Header){
h.Extra = v
return h
}