-
Notifications
You must be signed in to change notification settings - Fork 3
/
option.go
94 lines (79 loc) · 1.88 KB
/
option.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
package jwt
import (
"errors"
"time"
"github.com/golang-jwt/jwt"
)
var opt *options
// Init 初始化jwt
func Init(opts ...Option) {
o := defaultOptions()
o.apply(opts...)
opt = o
}
var (
defaultSigningKey = []byte("zaq12wsxmko0") // 默认
defaultSigningMethod = jwt.SigningMethodHS256 // 默认HS256
defaultExpire = 2 * time.Hour // 默认过期时长
defaultIssuer = ""
)
type options struct {
signingKey []byte
expire time.Duration
issuer string
signingMethod *jwt.SigningMethodHMAC
}
func defaultOptions() *options {
return &options{
signingKey: defaultSigningKey,
signingMethod: defaultSigningMethod,
expire: defaultExpire,
issuer: defaultIssuer,
}
}
// Option set the jwt options.
type Option func(*options)
func (o *options) apply(opts ...Option) {
for _, opt := range opts {
opt(o)
}
}
// WithSigningKey set signing key value
func WithSigningKey(key string) Option {
return func(o *options) {
o.signingKey = []byte(key)
}
}
// WithSigningMethod set signing method value
func WithSigningMethod(sm *jwt.SigningMethodHMAC) Option {
return func(o *options) {
o.signingMethod = sm
}
}
// WithExpire set expire value
func WithExpire(d time.Duration) Option {
return func(o *options) {
o.expire = d
}
}
// WithIssuer set issuer value
func WithIssuer(issuer string) Option {
return func(o *options) {
o.issuer = issuer
}
}
var (
// HS256 Method
HS256 = jwt.SigningMethodHS256
// HS384 Method
HS384 = jwt.SigningMethodHS384
// HS512 Method
HS512 = jwt.SigningMethodHS512
)
var (
errFormat = errors.New("invalid token format")
errExpired = errors.New("token has expired")
errUnverifiable = errors.New("the token could not be verified due to a signing problem")
errSignature = errors.New("signature failure")
errInit = errors.New("not yet initialized jwt, usage 'jwt.Init()'")
)