-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_token.go
102 lines (94 loc) · 2.55 KB
/
create_token.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
package jwt
import (
"fmt"
"html"
"time"
)
func (t *jwt) Create(claims *Claims, h ...*Headers) (string, error) {
// Init Headers
headers := t.config.Headers
if len(h) != 0 {
if h[0].Type != "" {
headers.Type = h[0].Type
}
if h[0].SignatureAlgorithm != "" {
headers.SignatureAlgorithm = h[0].SignatureAlgorithm
}
if h[0].ContentType != "" {
headers.ContentType = h[0].ContentType
}
if h[0].KeyId != "" {
headers.KeyId = h[0].KeyId
}
if h[0].Critical != "" {
headers.Critical = h[0].Critical
}
}
if headers.Type == "" {
return "", fmt.Errorf("headers.Type header must be present")
}
if headers.SignatureAlgorithm == "" {
return "", fmt.Errorf("headers.SignatureAlgorithm header must be present")
}
// Init Claims
if claims.Issuer == "" {
claims.Issuer = t.config.Claims.Issuer
}
if claims.Subject == "" {
claims.Subject = t.config.Claims.Subject
}
if claims.Audience == "" {
claims.Audience = t.config.Claims.Audience
}
if claims.ExpirationTime == 0 {
claims.ExpirationTime = t.config.Claims.ExpirationTime
}
if claims.NotBefore == 0 {
claims.NotBefore = t.config.Claims.NotBefore
}
if claims.IssuedAt == 0 {
claims.IssuedAt = t.config.Claims.IssuedAt
}
if claims.JwtId == "" {
claims.JwtId = t.config.Claims.JwtId
}
if claims.Data == nil {
claims.Data = t.config.Claims.Data
}
// Headers part
headersPart, err := createHeaderPart(&headers)
if err != nil {
return "", fmt.Errorf("failed to make the headersPart: %s", err)
}
// Payload part
now := time.Now().UTC().Unix()
if claims.IssuedAt == 0 {
claims.IssuedAt = now
}
if claims.NotBefore != 0 {
if claims.NotBefore < claims.IssuedAt {
return "", fmt.Errorf("claims.NotBefore cannot be less than claims.IssuedAt")
}
}
if claims.ExpirationTime == 0 {
if t.config.TokenLifetimeSec == 0 {
return "", fmt.Errorf("claims.ExpirationTime or config.TokenLifetimeSec must not be null")
}
claims.ExpirationTime =
time.Unix(now, 0).Add(time.Second * time.Duration(t.config.TokenLifetimeSec)).UTC().Unix()
}
claimsPart, err := createClaimsPart(claims)
if err != nil {
return "", fmt.Errorf("failed to make the claimsPart: %s", err)
}
// Signature
unsignedToken := headersPart + "." + claimsPart
signature, err := makeSignature(unsignedToken, headers.SignatureAlgorithm, t.config.Key)
if err != nil {
return "", fmt.Errorf("failed to make the signature: %s", err)
}
// Return the JSON Web Token (JWT).
return html.UnescapeString(headersPart) +
"." + html.UnescapeString(claimsPart) +
"." + html.UnescapeString(signature), nil
}