forked from StephanDollberg/go-json-rest-middleware-jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth_jwt.go
237 lines (191 loc) · 6.87 KB
/
auth_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
234
235
236
237
// Package jwt provides Json-Web-Token authentication for the go-json-rest framework
package jwt
import (
"github.com/ant0ine/go-json-rest/rest"
"github.com/dgrijalva/jwt-go"
"errors"
"log"
"net/http"
"strings"
"time"
)
// Middleware provides a Json-Web-Token authentication implementation. On failure, a 401 HTTP response
// is returned. On success, the wrapped middleware is called, and the userId is made available as
// request.Env["REMOTE_USER"].(string).
// Users can get a token by posting a json request to LoginHandler. The token then needs to be passed in
// the Authentication header. Example: Authorization:Bearer XXX_TOKEN_XXX
type Middleware struct {
// Realm name to display to the user. Required.
Realm string
// signing algorithm - possible values are HS256, HS384, HS512
// Optional, default is HS256.
SigningAlgorithm string
// Secret key used for signing. Required.
Key interface{}
// Secret key used for signing. Required.
VerifyKey interface{}
// Duration that a jwt token is valid. Optional, defaults to one hour.
Timeout time.Duration
// This field allows clients to refresh their token until MaxRefresh has passed.
// Note that clients can refresh their token in the last moment of MaxRefresh.
// This means that the maximum validity timespan for a token is MaxRefresh + Timeout.
// Optional, defaults to 0 meaning not refreshable.
MaxRefresh time.Duration
// Callback function that should perform the authentication of the user based on userId and
// password. Must return true on success, false on failure. Required.
Authenticator func(userId string, password string) error
// Callback function that should perform the authorization of the authenticated user. Called
// only after an authentication success. Must return true on success, false on failure.
// Optional, default to success.
Authorizator func(userId string, request *rest.Request) bool
// Callback function that will be called during login.
// Using this function it is possible to add additional payload data to the webtoken.
// The data is then made available during requests via request.Env["JWT_PAYLOAD"].
// Note that the payload is not encrypted.
// The attributes mentioned on jwt.io can't be used as keys for the map.
// Optional, by default no additional data will be set.
PayloadFunc func(userId string) map[string]interface{}
}
// MiddlewareFunc makes Middleware implement the Middleware interface.
func (mw *Middleware) MiddlewareFunc(handler rest.HandlerFunc) rest.HandlerFunc {
if mw.Realm == "" {
log.Fatal("Realm is required")
}
if mw.SigningAlgorithm == "" {
mw.SigningAlgorithm = "HS256"
}
if mw.Timeout == 0 {
mw.Timeout = time.Hour
}
if mw.Authenticator == nil {
log.Fatal("Authenticator is required")
}
if mw.Authorizator == nil {
mw.Authorizator = func(userId string, request *rest.Request) bool {
return true
}
}
return func(writer rest.ResponseWriter, request *rest.Request) {
mw.middlewareImpl(writer, request, handler)
}
}
func (mw *Middleware) middlewareImpl(writer rest.ResponseWriter, request *rest.Request, handler rest.HandlerFunc) {
token, err := mw.parseToken(request)
if err != nil {
mw.unauthorized(writer, err)
return
}
id := token.Claims["id"].(string)
request.Env["REMOTE_USER"] = id
request.Env["JWT_PAYLOAD"] = token.Claims
if !mw.Authorizator(id, request) {
mw.unauthorized(writer, errors.New("Not Authorized"))
return
}
handler(writer, request)
}
// ExtractClaims allows to retrieve the payload
func ExtractClaims(request *rest.Request) map[string]interface{} {
if request.Env["JWT_PAYLOAD"] == nil {
emptyClaims := make(map[string]interface{})
return emptyClaims
}
jwtClaims := request.Env["JWT_PAYLOAD"].(map[string]interface{})
return jwtClaims
}
type resultToken struct {
Token string `json:"token"`
}
type login struct {
Username string `json:"username"`
Password string `json:"password"`
}
// LoginHandler can be used by clients to get a jwt token.
// Payload needs to be json in the form of {"username": "USERNAME", "password": "PASSWORD"}.
// Reply will be of the form {"token": "TOKEN"}.
func (mw *Middleware) LoginHandler(writer rest.ResponseWriter, request *rest.Request) {
loginVals := login{}
err := request.DecodeJsonPayload(&loginVals)
if err != nil {
mw.unauthorized(writer, err)
return
}
err = mw.Authenticator(loginVals.Username, loginVals.Password)
if err != nil {
mw.unauthorized(writer, err)
return
}
token := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm))
if mw.PayloadFunc != nil {
for key, value := range mw.PayloadFunc(loginVals.Username) {
token.Claims[key] = value
}
}
token.Claims["id"] = loginVals.Username
token.Claims["exp"] = time.Now().Add(mw.Timeout).Unix()
if mw.MaxRefresh != 0 {
token.Claims["orig_iat"] = time.Now().Unix()
}
tokenString, err := token.SignedString(mw.Key)
if err != nil {
mw.unauthorized(writer, err)
return
}
writer.WriteJson(resultToken{Token: tokenString})
}
func (mw *Middleware) parseToken(request *rest.Request) (*jwt.Token, error) {
authHeader := request.Header.Get("Authorization")
if authHeader == "" {
return nil, errors.New("Auth header empty")
}
parts := strings.SplitN(authHeader, " ", 2)
if !(len(parts) == 2 && parts[0] == "Bearer") {
return nil, errors.New("Invalid auth header")
}
request.Env["JWT_RAW"] = parts[1]
return jwt.Parse(parts[1], func(token *jwt.Token) (interface{}, error) {
if jwt.GetSigningMethod(mw.SigningAlgorithm) != token.Method {
return nil, errors.New("Invalid signing algorithm")
}
if mw.VerifyKey != nil {
return mw.VerifyKey, nil
}
return mw.Key, nil
})
}
type token struct {
Token string `json:"token"`
}
// RefreshHandler can be used to refresh a token. The token still needs to be valid on refresh.
// Shall be put under an endpoint that is using the JWTMiddleware.
// Reply will be of the form {"token": "TOKEN"}.
func (mw *Middleware) RefreshHandler(writer rest.ResponseWriter, request *rest.Request) {
token, err := mw.parseToken(request)
// Token should be valid anyway as the RefreshHandler is authed
if err != nil {
mw.unauthorized(writer, err)
return
}
origIat := int64(token.Claims["orig_iat"].(float64))
if origIat < time.Now().Add(-mw.MaxRefresh).Unix() {
mw.unauthorized(writer, errors.New("Token Expired"))
return
}
newToken := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm))
for key := range token.Claims {
newToken.Claims[key] = token.Claims[key]
}
newToken.Claims["id"] = token.Claims["id"]
newToken.Claims["exp"] = time.Now().Add(mw.Timeout).Unix()
newToken.Claims["orig_iat"] = origIat
tokenString, err := newToken.SignedString(mw.Key)
if err != nil {
mw.unauthorized(writer, err)
return
}
writer.WriteJson(resultToken{Token: tokenString})
}
func (mw *Middleware) unauthorized(writer rest.ResponseWriter, err error) {
writer.Header().Set("WWW-Authenticate", "JWT realm="+mw.Realm)
rest.Error(writer, err.Error(), http.StatusUnauthorized)
}