-
Notifications
You must be signed in to change notification settings - Fork 206
/
Copy pathmiddleware_test.go
226 lines (207 loc) · 6.65 KB
/
middleware_test.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
package jwtmiddleware
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/auth0/go-jwt-middleware/v2/validator"
)
func Test_CheckJWT(t *testing.T) {
const (
validToken = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0ZXN0SXNzdWVyIiwiYXVkIjoidGVzdEF1ZGllbmNlIn0.Bg8HXYXZ13zaPAcB0Bl0kRKW0iVF-2LTmITcEYUcWoo"
invalidToken = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0ZXN0aW5nIn0.eM1Jd7VA7nFSI09FlmLmtuv7cLnv8qicZ8s76-jTOoE"
issuer = "testIssuer"
audience = "testAudience"
)
tokenClaims := &validator.ValidatedClaims{
RegisteredClaims: validator.RegisteredClaims{
Issuer: issuer,
Audience: []string{audience},
},
}
keyFunc := func(context.Context) (interface{}, error) {
return []byte("secret"), nil
}
jwtValidator, err := validator.New(keyFunc, validator.HS256, issuer, []string{audience})
require.NoError(t, err)
testCases := []struct {
name string
validateToken ValidateToken
options []Option
method string
token string
wantToken interface{}
wantStatusCode int
wantBody string
path string
}{
{
name: "it can successfully validate a token",
validateToken: jwtValidator.ValidateToken,
token: validToken,
method: http.MethodGet,
wantToken: tokenClaims,
wantStatusCode: http.StatusOK,
wantBody: `{"message":"Authenticated."}`,
},
{
name: "it can validate on options",
validateToken: jwtValidator.ValidateToken,
method: http.MethodOptions,
token: validToken,
wantToken: tokenClaims,
wantStatusCode: http.StatusOK,
wantBody: `{"message":"Authenticated."}`,
},
{
name: "it fails to validate a token with a bad format",
token: "bad",
method: http.MethodGet,
wantStatusCode: http.StatusInternalServerError,
wantBody: `{"message":"Something went wrong while checking the JWT."}`,
},
{
name: "it fails to validate if token is missing and credentials are not optional",
token: "",
method: http.MethodGet,
wantStatusCode: http.StatusBadRequest,
wantBody: `{"message":"JWT is missing."}`,
},
{
name: "it fails to validate an invalid token",
validateToken: jwtValidator.ValidateToken,
token: invalidToken,
method: http.MethodGet,
wantStatusCode: http.StatusUnauthorized,
wantBody: `{"message":"JWT is invalid."}`,
},
{
name: "it skips validation on OPTIONS if validateOnOptions is set to false",
options: []Option{
WithValidateOnOptions(false),
},
method: http.MethodOptions,
token: validToken,
wantStatusCode: http.StatusOK,
wantBody: `{"message":"Authenticated."}`,
},
{
name: "it fails validation if there are errors with the token extractor",
options: []Option{
WithTokenExtractor(func(r *http.Request) (string, error) {
return "", errors.New("token extractor error")
}),
},
method: http.MethodGet,
wantStatusCode: http.StatusInternalServerError,
wantBody: `{"message":"Something went wrong while checking the JWT."}`,
},
{
name: "credentialsOptional true",
options: []Option{
WithCredentialsOptional(true),
WithTokenExtractor(func(r *http.Request) (string, error) {
return "", nil
}),
},
method: http.MethodGet,
wantStatusCode: http.StatusOK,
wantBody: `{"message":"Authenticated."}`,
},
{
name: "it fails validation if we do not receive any token from " +
"a custom extractor and credentialsOptional is false",
options: []Option{
WithCredentialsOptional(false),
WithTokenExtractor(func(r *http.Request) (string, error) {
return "", nil
}),
},
method: http.MethodGet,
wantStatusCode: http.StatusBadRequest,
wantBody: `{"message":"JWT is missing."}`,
},
{
name: "JWT not required for /public",
options: []Option{
WithExclusionUrls([]string{"/public", "/health", "/special"}),
},
method: http.MethodGet,
path: "/public",
token: "",
wantStatusCode: http.StatusOK,
wantBody: `{"message":"Authenticated."}`,
},
{
name: "JWT not required for /health",
options: []Option{
WithExclusionUrls([]string{"/public", "/health", "/special"}),
},
method: http.MethodGet,
path: "/health",
token: "",
wantStatusCode: http.StatusOK,
wantBody: `{"message":"Authenticated."}`,
},
{
name: "JWT not required for /special",
options: []Option{
WithExclusionUrls([]string{"/public", "/health", "/special"}),
},
method: http.MethodGet,
path: "/special",
token: "",
wantStatusCode: http.StatusOK,
wantBody: `{"message":"Authenticated."}`,
},
{
name: "JWT required for /secure (not in exclusion list)",
options: []Option{
WithExclusionUrls([]string{"/public", "/health", "/special"}),
},
method: http.MethodGet,
path: "/secure",
token: "",
wantStatusCode: http.StatusBadRequest,
wantBody: `{"message":"JWT is missing."}`,
},
}
for _, testCase := range testCases {
testCase := testCase
t.Run(testCase.name, func(t *testing.T) {
t.Parallel()
middleware := New(testCase.validateToken, testCase.options...)
var actualValidatedClaims interface{}
var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
actualValidatedClaims = r.Context().Value(ContextKey{})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"message":"Authenticated."}`))
})
testServer := httptest.NewServer(middleware.CheckJWT(handler))
defer testServer.Close()
url := testServer.URL + testCase.path
request, err := http.NewRequest(testCase.method, url, nil)
require.NoError(t, err)
if testCase.token != "" {
request.Header.Add("Authorization", testCase.token)
}
response, err := testServer.Client().Do(request)
require.NoError(t, err)
body, err := io.ReadAll(response.Body)
require.NoError(t, err)
defer response.Body.Close()
assert.Equal(t, testCase.wantStatusCode, response.StatusCode)
assert.Equal(t, "application/json", response.Header.Get("Content-Type"))
assert.Equal(t, testCase.wantBody, string(body))
if want, got := testCase.wantToken, actualValidatedClaims; !cmp.Equal(want, got) {
t.Fatal(cmp.Diff(want, got))
}
})
}
}