-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathjwt.go
233 lines (204 loc) · 7.22 KB
/
jwt.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package oauth2
import (
"crypto/subtle"
"fmt"
"time"
jose "github.com/go-jose/go-jose/v4"
"github.com/go-jose/go-jose/v4/jwt"
"github.com/nilorg/pkg/slice"
"github.com/nilorg/sdk/strings"
)
// 参考 https://github.com/dgrijalva/jwt-go/blob/master/claims.go
// ----- helpers
func verifyAud(aud []string, cmp []string, required bool) bool {
if len(aud) == 0 {
return !required
}
return slice.IsSubset(cmp, aud)
}
func verifyExp(exp int64, now int64, required bool) bool {
if exp == 0 {
return !required
}
return now <= exp
}
func verifyIat(iat int64, now int64, required bool) bool {
if iat == 0 {
return !required
}
return now >= iat
}
func verifyIss(iss string, cmp string, required bool) bool {
if iss == "" {
return !required
}
return subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0
}
func verifyNbf(nbf int64, now int64, required bool) bool {
if nbf == 0 {
return !required
}
return now >= nbf
}
func verifyScope(scope []string, cmp []string, required bool) bool {
if len(scope) == 0 {
return !required
}
return slice.IsSubset(cmp, scope)
}
// JwtStandardClaims as referenced at
// https://tools.ietf.org/html/rfc7519#section-4.1
type JwtStandardClaims struct {
Audience []string `json:"aud,omitempty"`
ExpiresAt int64 `json:"exp,omitempty"`
ID string `json:"jti,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
Issuer string `json:"iss,omitempty"`
NotBefore int64 `json:"nbf,omitempty"`
Subject string `json:"sub,omitempty"`
}
// Valid time based claims "exp, iat, nbf".
// There is no accounting for clock skew.
// As well, if any of the above claims are not in the token, it will still
// be considered a valid claim.
func (c JwtStandardClaims) Valid() error {
now := time.Now().Unix()
// The claims below are optional, by default, so if they are set to the
// default value in Go, let's not fail the verification for them.
if !c.VerifyExpiresAt(now, false) {
delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0))
return fmt.Errorf("token is expired by %v", delta)
}
if !c.VerifyIssuedAt(now, false) {
return fmt.Errorf("Token used before issued")
}
if !c.VerifyNotBefore(now, false) {
return fmt.Errorf("token is not valid yet")
}
return nil
}
// VerifyAudience Compares the aud claim against cmp.
// If required is false, this method will return true if the value matches or is unset
// 如果required为false,如果值匹配或未设置,此方法将返回true
func (c *JwtStandardClaims) VerifyAudience(cmp []string, req bool) bool {
return verifyAud(c.Audience, cmp, req)
}
// VerifyExpiresAt Compares the exp claim against cmp.
// If required is false, this method will return true if the value matches or is unset
// 如果required为false,如果值匹配或未设置,此方法将返回true
func (c *JwtStandardClaims) VerifyExpiresAt(cmp int64, req bool) bool {
return verifyExp(c.ExpiresAt, cmp, req)
}
// VerifyIssuedAt Compares the iat claim against cmp.
// If required is false, this method will return true if the value matches or is unset
// 如果required为false,如果值匹配或未设置,此方法将返回true
func (c *JwtStandardClaims) VerifyIssuedAt(cmp int64, req bool) bool {
return verifyIat(c.IssuedAt, cmp, req)
}
// VerifyIssuer Compares the iss claim against cmp.
// If required is false, this method will return true if the value matches or is unset
// 如果required为false,如果值匹配或未设置,此方法将返回true
func (c *JwtStandardClaims) VerifyIssuer(cmp string, req bool) bool {
return verifyIss(c.Issuer, cmp, req)
}
// VerifyNotBefore Compares the nbf claim against cmp.
// If required is false, this method will return true if the value matches or is unset
// 如果required为false,如果值匹配或未设置,此方法将返回true
func (c *JwtStandardClaims) VerifyNotBefore(cmp int64, req bool) bool {
return verifyNbf(c.NotBefore, cmp, req)
}
// JwtClaims 在jwt标准上的扩展
type JwtClaims struct {
JwtStandardClaims
Scope string `json:"scope,omitempty"`
}
// VerifyScope Compares the aud claim against cmp.
// If required is false, this method will return true if the value matches or is unset
// 如果required为false,如果值匹配或未设置,此方法将返回true
func (c *JwtClaims) VerifyScope(scope string, req bool) bool {
source := strings.Split(c.Scope, " ")
array := strings.Split(scope, " ")
return verifyScope(source, array, req)
}
// NewJwtClaims ...
func NewJwtClaims(issuer, audience, scope, openID string) *JwtClaims {
currTime := time.Now()
return &JwtClaims{
JwtStandardClaims: JwtStandardClaims{
// Issuer = iss,令牌颁发者。它表示该令牌是由谁创建的
Issuer: issuer,
// Subject = sub,令牌的主体。它表示该令牌是关于谁的
Subject: openID,
// Audience = aud,令牌的受众。它表示令牌的接收者
Audience: []string{audience},
// ExpiresAt = exp,令牌的过期时间戳。它表示令牌将在何时过期
ExpiresAt: currTime.Add(AccessTokenExpire).Unix(),
// NotBefore = nbf,令牌的生效时的时间戳。它表示令牌从什么时候开始生效
NotBefore: currTime.Unix(),
// IssuedAt = iat,令牌颁发时的时间戳。它表示令牌是何时被创建的
IssuedAt: currTime.Unix(),
},
Scope: scope,
}
}
func newJwtToken(v interface{}, algorithm string, key interface{}) (token string, err error) {
var sig jose.Signer
sig, err = jose.NewSigner(
jose.SigningKey{
Algorithm: jose.SignatureAlgorithm(algorithm),
Key: key,
},
(&jose.SignerOptions{}).WithType("JWT"),
)
if err != nil {
return
}
token, err = jwt.Signed(sig).Claims(v).Serialize()
return
}
// NewJwtToken ...
func NewJwtToken(v interface{}, algorithm string, key interface{}) (string, error) {
return newJwtToken(v, algorithm, key)
}
// NewJwtClaimsToken ...
func NewJwtClaimsToken(claims *JwtClaims, algorithm string, key interface{}) (string, error) {
return newJwtToken(claims, algorithm, key)
}
// NewJwtStandardClaimsToken ...
func NewJwtStandardClaimsToken(claims *JwtStandardClaims, algorithm string, key interface{}) (string, error) {
return newJwtToken(claims, algorithm, key)
}
// NewHS256JwtClaimsToken ...
func NewHS256JwtClaimsToken(claims *JwtClaims, jwtVerifyKey []byte) (string, error) {
return newJwtToken(claims, "HS256", jwtVerifyKey)
}
// parseJwtToken ...
func parseJwtToken(token string, algorithm string, key interface{}, dest ...interface{}) (err error) {
var (
tok *jwt.JSONWebToken
)
tok, err = jwt.ParseSigned(token, []jose.SignatureAlgorithm{
jose.SignatureAlgorithm(algorithm),
})
if err != nil {
return
}
err = tok.Claims(key, dest...)
return
}
// ParseJwtClaimsToken ...
func ParseJwtClaimsToken(token string, algorithm string, key interface{}) (claims *JwtClaims, err error) {
claims = new(JwtClaims)
err = parseJwtToken(token, algorithm, key, claims)
return
}
// ParseJwtStandardClaimsToken ...
func ParseJwtStandardClaimsToken(token string, algorithm string, key interface{}) (claims *JwtStandardClaims, err error) {
claims = new(JwtStandardClaims)
err = parseJwtToken(token, algorithm, key, claims)
return
}
// ParseHS256JwtClaimsToken ...
func ParseHS256JwtClaimsToken(token string, jwtVerifyKey []byte) (claims *JwtClaims, err error) {
return ParseJwtClaimsToken(token, "HS256", jwtVerifyKey)
}