forked from ory/fosite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
claims_jwt.go
70 lines (59 loc) · 1.48 KB
/
claims_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
package jwt
import (
"time"
"github.com/pborman/uuid"
)
func JWTClaimsFromMap(m map[string]interface{}) *JWTClaims {
return &JWTClaims{
Subject: ToString(m["sub"]),
IssuedAt: ToTime(m["iat"]),
Issuer: ToString(m["iss"]),
NotBefore: ToTime(m["nbf"]),
Audience: ToString(m["aud"]),
ExpiresAt: ToTime(m["exp"]),
JTI: ToString(m["jti"]),
Extra: Filter(m, "sub", "iss", "iat", "nbf", "aud", "exp", "jti"),
}
}
// JWTClaims represent a token's claims.
type JWTClaims struct {
Subject string
Issuer string
Audience string
JTI string
IssuedAt time.Time
NotBefore time.Time
ExpiresAt time.Time
Extra map[string]interface{}
}
func (c *JWTClaims) ToMap() map[string]interface{} {
var ret = Copy(c.Extra)
ret["jti"] = c.JTI
if c.JTI == "" {
ret["jti"] = uuid.New()
}
ret["sub"] = c.Subject
ret["iss"] = c.Issuer
ret["aud"] = c.Audience
ret["iat"] = c.IssuedAt.Unix()
ret["nbf"] = c.NotBefore.Unix()
ret["exp"] = c.ExpiresAt.Unix()
return ret
}
func (c JWTClaims) Get(key string) interface{} {
return c.ToMap()[key]
}
func (c *JWTClaims) Add(key string, value interface{}) {
if c.Extra == nil {
c.Extra = make(map[string]interface{})
}
c.Extra[key] = value
}
// IsExpired checks if JWT is expired.
func (c *JWTClaims) IsExpired() bool {
return c.ExpiresAt.Before(time.Now())
}
// IsNotYetValid maskes sure that the JWT is not used before valid date.
func (c *JWTClaims) IsNotYetValid() bool {
return c.NotBefore.After(time.Now())
}