forked from StephanDollberg/go-json-rest-middleware-jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_jwt_test.go
More file actions
217 lines (186 loc) · 7.56 KB
/
auth_jwt_test.go
File metadata and controls
217 lines (186 loc) · 7.56 KB
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
package jwt
import (
"github.com/ant0ine/go-json-rest/rest"
"github.com/ant0ine/go-json-rest/rest/test"
"github.com/dgrijalva/jwt-go"
"testing"
"time"
)
type DecoderToken struct {
Token string `json:"token"`
}
func makeTokenString(username string, key []byte) string {
token := jwt.New(jwt.GetSigningMethod("HS256"))
token.Claims["id"] = "admin"
token.Claims["exp"] = time.Now().Add(time.Hour).Unix()
token.Claims["orig_iat"] = time.Now().Unix()
tokenString, _ := token.SignedString(key)
return tokenString
}
func TestAuthJWT(t *testing.T) {
key := []byte("secret key")
// the middleware to test
authMiddleware := &JWTMiddleware{
Realm: "test zone",
Key: key,
Timeout: time.Hour,
MaxRefresh: time.Hour * 24,
Authenticator: func(userId string, password string) bool {
if userId == "admin" && password == "admin" {
return true
}
return false
},
Authorizator: func(userId string, request *rest.Request) bool {
if request.Method == "GET" {
return true
}
return false
},
}
// api for testing failure
apiFailure := rest.NewApi()
apiFailure.Use(authMiddleware)
apiFailure.SetApp(rest.AppSimple(func(w rest.ResponseWriter, r *rest.Request) {
t.Error("Should never be executed")
}))
handler := apiFailure.MakeHandler()
// simple request fails
recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/", nil))
recorded.CodeIs(401)
recorded.ContentTypeIsJson()
// auth with right cred and wrong method fails
wrongMethodReq := test.MakeSimpleRequest("POST", "http://localhost/", nil)
wrongMethodReq.Header.Set("Authorization", "Bearer "+makeTokenString("admin", key))
recorded = test.RunRequest(t, handler, wrongMethodReq)
recorded.CodeIs(401)
recorded.ContentTypeIsJson()
// wrong Auth format - bearer lower case
wrongAuthFormat := test.MakeSimpleRequest("GET", "http://localhost/", nil)
wrongAuthFormat.Header.Set("Authorization", "bearer "+makeTokenString("admin", key))
recorded = test.RunRequest(t, handler, wrongAuthFormat)
recorded.CodeIs(401)
recorded.ContentTypeIsJson()
// wrong Auth format - no space after bearer
wrongAuthFormat = test.MakeSimpleRequest("GET", "http://localhost/", nil)
wrongAuthFormat.Header.Set("Authorization", "bearer"+makeTokenString("admin", key))
recorded = test.RunRequest(t, handler, wrongAuthFormat)
recorded.CodeIs(401)
recorded.ContentTypeIsJson()
// wrong Auth format - empty auth header
wrongAuthFormat = test.MakeSimpleRequest("GET", "http://localhost/", nil)
wrongAuthFormat.Header.Set("Authorization", "")
recorded = test.RunRequest(t, handler, wrongAuthFormat)
recorded.CodeIs(401)
recorded.ContentTypeIsJson()
// right credt, right method but wrong priv key
wrongPrivKeyReq := test.MakeSimpleRequest("GET", "http://localhost/", nil)
wrongPrivKeyReq.Header.Set("Authorization", "Bearer "+makeTokenString("admin", []byte("sekret key")))
recorded = test.RunRequest(t, handler, wrongPrivKeyReq)
recorded.CodeIs(401)
recorded.ContentTypeIsJson()
// right credt, right method, right priv key but timeout
token := jwt.New(jwt.GetSigningMethod("HS256"))
token.Claims["id"] = "admin"
token.Claims["exp"] = 0
tokenString, _ := token.SignedString(key)
expiredTimestampReq := test.MakeSimpleRequest("GET", "http://localhost/", nil)
expiredTimestampReq.Header.Set("Authorization", "Bearer "+tokenString)
recorded = test.RunRequest(t, handler, expiredTimestampReq)
recorded.CodeIs(401)
recorded.ContentTypeIsJson()
// api for testing success
apiSuccess := rest.NewApi()
apiSuccess.Use(authMiddleware)
apiSuccess.SetApp(rest.AppSimple(func(w rest.ResponseWriter, r *rest.Request) {
if r.Env["REMOTE_USER"] == nil {
t.Error("REMOTE_USER is nil")
}
user := r.Env["REMOTE_USER"].(string)
if user != "admin" {
t.Error("REMOTE_USER is expected to be 'admin'")
}
w.WriteJson(map[string]string{"Id": "123"})
}))
// auth with right cred and right method succeeds
validReq := test.MakeSimpleRequest("GET", "http://localhost/", nil)
validReq.Header.Set("Authorization", "Bearer "+makeTokenString("admin", key))
recorded = test.RunRequest(t, apiSuccess.MakeHandler(), validReq)
recorded.CodeIs(200)
recorded.ContentTypeIsJson()
// login tests
loginApi := rest.NewApi()
loginApi.SetApp(rest.AppSimple(authMiddleware.LoginHandler))
// wrong login
wrongLoginCreds := map[string]string{"username": "admin", "password": "admIn"}
wrongLoginReq := test.MakeSimpleRequest("POST", "http://localhost/", wrongLoginCreds)
recorded = test.RunRequest(t, loginApi.MakeHandler(), wrongLoginReq)
recorded.CodeIs(401)
recorded.ContentTypeIsJson()
// empty login
emptyLoginCreds := map[string]string{}
emptyLoginReq := test.MakeSimpleRequest("POST", "http://localhost/", emptyLoginCreds)
recorded = test.RunRequest(t, loginApi.MakeHandler(), emptyLoginReq)
recorded.CodeIs(401)
recorded.ContentTypeIsJson()
// correct login
before := time.Now().Unix()
loginCreds := map[string]string{"username": "admin", "password": "admin"}
rightCredReq := test.MakeSimpleRequest("POST", "http://localhost/", loginCreds)
recorded = test.RunRequest(t, loginApi.MakeHandler(), rightCredReq)
recorded.CodeIs(200)
recorded.ContentTypeIsJson()
nToken := DecoderToken{}
test.DecodeJsonPayload(recorded.Recorder, &nToken)
newToken, err := jwt.Parse(nToken.Token, func(token *jwt.Token) (interface{}, error) {
return key, nil
})
if err != nil {
t.Errorf("Received new token with wrong signature", err)
}
if newToken.Claims["id"].(string) != "admin" ||
int64(newToken.Claims["exp"].(float64)) < before {
t.Errorf("Received new token with wrong data")
}
refreshApi := rest.NewApi()
refreshApi.Use(authMiddleware)
refreshApi.SetApp(rest.AppSimple(authMiddleware.RefreshHandler))
// refresh with expired max refresh
unrefreshableToken := jwt.New(jwt.GetSigningMethod("HS256"))
unrefreshableToken.Claims["id"] = "admin"
// the combination actually doesn't make sense but is ok for the test
unrefreshableToken.Claims["exp"] = time.Now().Add(time.Hour).Unix()
unrefreshableToken.Claims["orig_iat"] = 0
tokenString, _ = unrefreshableToken.SignedString(key)
unrefreshableReq := test.MakeSimpleRequest("GET", "http://localhost/", nil)
unrefreshableReq.Header.Set("Authorization", "Bearer "+tokenString)
recorded = test.RunRequest(t, refreshApi.MakeHandler(), unrefreshableReq)
recorded.CodeIs(401)
recorded.ContentTypeIsJson()
// valid refresh
refreshableToken := jwt.New(jwt.GetSigningMethod("HS256"))
refreshableToken.Claims["id"] = "admin"
// we need to substract one to test the case where token is being created in
// the same second as it is checked -> < wouldn't fail
refreshableToken.Claims["exp"] = time.Now().Add(time.Hour).Unix() - 1
refreshableToken.Claims["orig_iat"] = time.Now().Unix() - 1
tokenString, _ = refreshableToken.SignedString(key)
validRefreshReq := test.MakeSimpleRequest("GET", "http://localhost/", nil)
validRefreshReq.Header.Set("Authorization", "Bearer "+tokenString)
recorded = test.RunRequest(t, refreshApi.MakeHandler(), validRefreshReq)
recorded.CodeIs(200)
recorded.ContentTypeIsJson()
rToken := DecoderToken{}
test.DecodeJsonPayload(recorded.Recorder, &rToken)
refreshToken, err := jwt.Parse(rToken.Token, func(token *jwt.Token) (interface{}, error) {
return key, nil
})
if err != nil {
t.Errorf("Received refreshed token with wrong signature", err)
}
if refreshToken.Claims["id"].(string) != "admin" ||
int64(refreshToken.Claims["orig_iat"].(float64)) != refreshableToken.Claims["orig_iat"].(int64) ||
int64(refreshToken.Claims["exp"].(float64)) < refreshableToken.Claims["exp"].(int64) {
t.Errorf("Received refreshed token with wrong data")
}
}