-
Notifications
You must be signed in to change notification settings - Fork 2
/
guard_jwt_token.go
254 lines (201 loc) · 6.05 KB
/
guard_jwt_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
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// Copyright © 2014-2023 Thomas Rabaix <thomas.rabaix@gmail.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package guard
import (
"encoding/json"
"fmt"
"net/http"
"regexp"
"github.com/dgrijalva/jwt-go"
"github.com/dgrijalva/jwt-go/request"
"github.com/rande/gonode/core/security"
log "github.com/sirupsen/logrus"
)
// Extract token from cookie request.
type CookieExtractor struct {
CookieName string
}
func (e *CookieExtractor) ExtractToken(req *http.Request) (string, error) {
// Make sure form is parsed
token, err := req.Cookie(e.CookieName)
if err == http.ErrNoCookie {
return "", request.ErrNoTokenInRequest
}
return token.Value, nil
}
// Extractor for OAuth2 access tokens. Looks in 'Authorization'
// header then 'access_token' argument for a token.
var OAuth2Extractor = &request.MultiExtractor{
&CookieExtractor{
CookieName: "access_token",
},
request.AuthorizationHeaderExtractor,
request.ArgumentExtractor{"access_token"},
}
// this authenticator will create a JWT Token from a standard form
type JwtTokenGuardAuthenticator struct {
Apply *regexp.Regexp // url to intercept as it is a login request
Ignore []*regexp.Regexp
Manager GuardManager
Validity int64
Key []byte
Logger *log.Logger
LoginPage string // url to redirect to if the token is not valid
}
func (a *JwtTokenGuardAuthenticator) GetCredentials(req *http.Request) (interface{}, error) {
for _, ignore := range a.Ignore {
if ignore.Match([]byte(req.URL.Path)) {
if a.Logger != nil {
a.Logger.WithFields(log.Fields{
"module": "core.guard.jwt_token",
"path": req.URL.Path,
"regexp": ignore,
}).Info("Ignore path, skipping")
}
return nil, nil
}
}
if !a.Apply.Match([]byte(req.URL.Path)) {
if a.Logger != nil {
a.Logger.WithFields(log.Fields{
"module": "core.guard.jwt_token",
"path": req.URL.Path,
"regexp": a.Apply,
}).Info("Invalid path, skipping")
}
return nil, nil
}
credentials, err := request.ParseFromRequest(req, OAuth2Extractor, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
if a.Logger != nil {
a.Logger.WithFields(log.Fields{
"module": "core.guard.jwt_token",
"algo": token.Header["alg"],
}).Info("Invalid signing method")
}
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(a.Key), nil
})
// no error, no credentials, nothing to do.
if credentials == nil && err == nil {
return nil, nil
}
if credentials != nil && err == nil {
claims := credentials.Claims.(jwt.MapClaims)
if _, ok := claims["usr"]; !ok {
if a.Logger != nil {
a.Logger.WithFields(log.Fields{
"module": "core.guard.jwt_token",
}).Info("invalid credentials, missing usr field")
}
return nil, ErrInvalidCredentialsFormat
}
if a.Logger != nil {
a.Logger.WithFields(log.Fields{
"module": "core.guard.jwt_token",
"username": claims["usr"],
"roles": claims["rls"],
}).Info("valid credentials")
}
return credentials, nil
}
// we have an error
if err == request.ErrNoTokenInRequest {
if a.Logger != nil {
a.Logger.WithFields(log.Fields{
"module": "core.guard.jwt_token",
"error": err.Error(),
}).Debug("No token in request, skipping")
}
return nil, nil
}
if e, ok := err.(*jwt.ValidationError); ok {
if (e.Errors & jwt.ValidationErrorExpired) != 0 {
if a.Logger != nil {
a.Logger.WithFields(log.Fields{
"module": "core.guard.jwt_token",
"error": err.Error(),
"code": e.Errors,
}).Warn("Token expired, please refresh it")
}
return nil, ErrTokenExpired
}
}
if a.Logger != nil {
a.Logger.WithFields(log.Fields{
"module": "core.guard.jwt_token",
"error": err.Error(),
}).Warn("Invalid credentials format")
}
return nil, ErrInvalidCredentialsFormat
}
func (a *JwtTokenGuardAuthenticator) GetUser(credentials interface{}) (GuardUser, error) {
jwtToken := credentials.(*jwt.Token)
claims := jwtToken.Claims.(jwt.MapClaims)
user, err := a.Manager.GetUser(claims["usr"].(string))
if err != nil {
if a.Logger != nil {
a.Logger.WithFields(log.Fields{
"module": "core.guard.jwt_token",
"error": err.Error(),
"username": claims["usr"].(string),
}).Error("An error occurs when retrieving the user")
}
return user, err
}
if user != nil {
return user, nil
}
if a.Logger != nil {
a.Logger.WithFields(log.Fields{
"module": "core.guard.jwt_token",
"username": claims["usr"].(string),
}).Info("Unable to found the user")
}
return nil, ErrUnableRetrieveUser
}
func (a *JwtTokenGuardAuthenticator) CheckCredentials(credentials interface{}, user GuardUser) error {
// nothing to do ...
return nil
}
func (a *JwtTokenGuardAuthenticator) CreateAuthenticatedToken(user GuardUser) (GuardToken, error) {
return &DefaultGuardToken{
Username: user.GetUsername(),
Roles: user.GetRoles(),
}, nil
}
func (a *JwtTokenGuardAuthenticator) OnAuthenticationFailure(req *http.Request, res http.ResponseWriter, err error) bool {
if req.Header.Get("Accept") == "application/json" {
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(http.StatusForbidden)
data, _ := json.Marshal(map[string]string{
"status": "KO",
"message": "Unable to validate the token",
})
res.Write(data)
return true
}
// redirect to the login page
if a.LoginPage != "" && err == ErrTokenExpired {
http.Redirect(res, req, a.LoginPage+"?reason=token_expired", http.StatusFound)
return true
}
if a.LoginPage != "" && err == ErrInvalidCredentialsFormat {
http.Redirect(res, req, a.LoginPage+"?reason=invalid_format", http.StatusFound)
return true
}
if err == ErrTokenExpired {
security.RenderExpiredToken(res)
} else {
security.RenderForbidden(res)
}
return true
}
func (a *JwtTokenGuardAuthenticator) OnAuthenticationSuccess(req *http.Request, res http.ResponseWriter, token GuardToken) bool {
// nothing to do
return false
}