/
jwt_service.go
212 lines (181 loc) · 5.73 KB
/
jwt_service.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
package jwtservice
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/jake-hansen/agora/domain"
)
const (
USAGE_AUTH = "auth"
USAGE_REFRESH = "refresh"
)
// JWTService is a service for generating and validating JWTs.
type JWTService interface {
GenerateAuthToken(user domain.User) (*domain.AuthToken, error)
GenerateRefreshToken(user domain.User, authToken domain.AuthToken, parentToken *domain.RefreshToken) (*domain.RefreshToken, error)
ValidateAuthToken(token domain.TokenValue) (domain.AuthToken, error)
ValidateRefreshToken(token domain.TokenValue) (domain.RefreshToken, error)
}
// Config contains the parameters for configuring a JWTService.
type Config struct {
Issuer string
SigningKey string
Duration time.Duration
RefreshDuration time.Duration
}
// JWTServiceImpl is an implementation of a JWTService.
type JWTServiceImpl struct {
config Config
}
// GenerateToken creates a JWT for the specified User and returns the token.
func (j *JWTServiceImpl) GenerateAuthToken(user domain.User) (*domain.AuthToken, error) {
now := time.Now()
expiry := now.Add(j.config.Duration)
claims := &domain.AuthClaims{
StandardClaims: jwt.StandardClaims{
ExpiresAt: expiry.Unix(),
IssuedAt: now.Unix(),
Issuer: j.config.Issuer,
NotBefore: now.Unix(),
Subject: user.Username,
},
UserID: user.ID,
Usage: USAGE_AUTH,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
t, err := token.SignedString([]byte(j.config.SigningKey))
if err != nil {
return nil, err
}
domainToken := &domain.AuthToken{
Value: domain.TokenValue(t),
Expires: expiry,
JWTClaims: *claims,
}
return domainToken, nil
}
// GenerateRefreshToken creates a Refresh JWT for the specified User and returns the token.
func (j *JWTServiceImpl) GenerateRefreshToken(user domain.User, authToken domain.AuthToken, parentToken *domain.RefreshToken) (*domain.RefreshToken, error) {
now := time.Now()
newExpiry := now.Add(j.config.RefreshDuration)
if parentToken != nil {
newExpiry = parentToken.ExpiresAt
}
authSHA := hash(string(authToken.Value))
parentRefreshSHA := ""
nonce := ""
nonceSHA := ""
if parentToken != nil {
parentRefreshSHA = parentToken.Hash()
nonce = parentToken.JWTClaims.Nonce
nonceSHA = parentToken.TokenNonceHash
} else {
generatedNonce, err := j.generateNonce()
if err != nil {
return nil, err
}
nonce = generatedNonce
nonceSHA = hash(nonce)
}
claims := &domain.RefreshClaims{
StandardClaims: jwt.StandardClaims{
ExpiresAt: newExpiry.Unix(),
IssuedAt: now.Unix(),
Issuer: j.config.Issuer,
NotBefore: now.Unix(),
Subject: user.Username,
},
UserID: user.ID,
AuthTokenHash: authSHA,
ParentTokenHash: parentRefreshSHA,
Nonce: nonce,
Usage: USAGE_REFRESH,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
t, err := token.SignedString([]byte(j.config.SigningKey))
if err != nil {
return nil, err
}
domainToken := &domain.RefreshToken{
Value: domain.TokenValue(t),
ExpiresAt: newExpiry,
ParentTokenHash: parentRefreshSHA,
TokenNonceHash: nonceSHA,
UserID: user.ID,
JWTClaims: *claims,
}
return domainToken, nil
}
// ValidateAuthToken validates the given TokenValue as an AuthToken. If the token is valid, the token is returned as
// an AuthToken. Otherwise, a nil token is returned along with an error.
func (j *JWTServiceImpl) ValidateAuthToken(token domain.TokenValue) (domain.AuthToken, error) {
var claims *domain.AuthClaims
_, err := jwt.ParseWithClaims(string(token), &domain.AuthClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
if tclaims, ok := token.Claims.(*domain.AuthClaims); ok {
if tclaims.Usage != USAGE_AUTH {
return nil, errors.New("token is not an auth token")
}
claims = tclaims
}
return []byte(j.config.SigningKey), nil
})
if err != nil {
return domain.AuthToken{}, err
}
returnToken := domain.AuthToken{
Value: token,
Expires: time.Unix(claims.ExpiresAt, 0),
JWTClaims: *claims,
}
return returnToken, err
}
// ValidateRefreshToken validates the given TokenValue as a RefreshToken. If the token is valid, the token is returned as
// a RefreshToken. Otherwise, a nil token is returned along with an error.
func (j *JWTServiceImpl) ValidateRefreshToken(token domain.TokenValue) (domain.RefreshToken, error) {
var claims *domain.RefreshClaims
_, err := jwt.ParseWithClaims(string(token), &domain.RefreshClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
if tclaims, ok := token.Claims.(*domain.RefreshClaims); ok {
if tclaims.Usage != USAGE_REFRESH {
return nil, errors.New("token is not an refresh token")
}
claims = tclaims
}
return []byte(j.config.SigningKey), nil
})
if err != nil {
return domain.RefreshToken{}, err
}
returnToken := domain.RefreshToken{
Value: token,
ExpiresAt: time.Unix(claims.ExpiresAt, 0),
TokenNonceHash: hash(claims.Nonce),
ParentTokenHash: claims.ParentTokenHash,
UserID: claims.UserID,
Revoked: false,
JWTClaims: *claims,
}
return returnToken, err
}
func (j *JWTServiceImpl) generateNonce() (string, error) {
b := make([]byte, 64)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
func hash(v string) string {
hasher := sha256.New()
hasher.Write([]byte(v))
value := hex.EncodeToString(hasher.Sum(nil))
return value
}