-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjwtverifier_test.go
269 lines (236 loc) · 8.67 KB
/
jwtverifier_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
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package jwtverifier
import (
"context"
"io/ioutil"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
type FakeStorageAdapter struct{}
func (a *FakeStorageAdapter) Set(token string, exp int64, introspect []byte) error {
return nil
}
func (a *FakeStorageAdapter) Get(t string) ([]byte, error) {
return nil, nil
}
func (a *FakeStorageAdapter) Delete(token string) error {
return nil
}
func TestSetAdapter(t *testing.T) {
jwt := createJwtVerifier("http://localhost")
jwt.SetStorage(&FakeStorageAdapter{})
if reflect.TypeOf(jwt.storage).String() != "*jwtverifier.FakeStorageAdapter" {
t.Error("Unable to set storage adapter")
}
}
func TestCreateAuthUrl(t *testing.T) {
jwt := createJwtVerifier("http://localhost")
url := jwt.CreateAuthUrl("mystate")
expected := "http://localhost/oauth2/auth?client_id=CLIENT_ID&redirect_uri=REDIRECT_URL&response_type=code&scope=scope&state=mystate"
if expected != url {
t.Errorf("Invalid auth URL [%s], expected [%s]", url, expected)
}
}
func TestCreateAuthUrl_WithOptions(t *testing.T) {
opt := AuthUrlOption{Key: "optionkey", Value: "optionvalue"}
jwt := createJwtVerifier("http://localhost")
url := jwt.CreateAuthUrl("mystate", opt)
expected := "http://localhost/oauth2/auth?client_id=CLIENT_ID&optionkey=optionvalue&redirect_uri=REDIRECT_URL&response_type=code&scope=scope&state=mystate"
if expected != url {
t.Errorf("Invalid auth URL [%s], expected [%s]", url, expected)
}
}
func TestCreateAuthUrl_WithManyOptions(t *testing.T) {
opt1 := AuthUrlOption{Key: "optionkey1", Value: "optionvalue1"}
opt2 := AuthUrlOption{Key: "optionkey2", Value: "optionvalue2"}
jwt := createJwtVerifier("http://localhost")
url := jwt.CreateAuthUrl("mystate", opt1, opt2)
expected := "http://localhost/oauth2/auth?client_id=CLIENT_ID&optionkey1=optionvalue1&optionkey2=optionvalue2&redirect_uri=REDIRECT_URL&response_type=code&scope=scope&state=mystate"
if expected != url {
t.Errorf("Invalid auth URL [%s], expected [%s]", url, expected)
}
}
func TestExchangeRequest(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.String() != "/oauth2/token" {
t.Errorf("Unexpected exchange request URL %q", r.URL)
}
headerAuth := r.Header.Get("Authorization")
if want := "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ="; headerAuth != want {
t.Errorf("Unexpected authorization header %q, want %q", headerAuth, want)
}
headerContentType := r.Header.Get("Content-Type")
if headerContentType != "application/x-www-form-urlencoded" {
t.Errorf("Unexpected Content-Type header %q", headerContentType)
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Errorf("Failed reading request body: %s.", err)
}
if string(body) != "code=exchange-code&grant_type=authorization_code&redirect_uri=REDIRECT_URL" {
t.Errorf("Unexpected exchange payload; got %q", body)
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"access_token": "90d64460d14870c08c81352a05dedd3465940a7c", "scope": "user", "token_type": "bearer", "expires_in": 86400}`))
}))
defer ts.Close()
jwt := createJwtVerifier(ts.URL)
tok, err := jwt.Exchange(context.Background(), "exchange-code")
if err != nil {
t.Error(err)
}
if !tok.Valid() {
t.Fatalf("Token invalid. Got: %#v", tok)
}
if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" {
t.Errorf("Unexpected access token, %#v.", tok.AccessToken)
}
if tok.TokenType != "bearer" {
t.Errorf("Unexpected token type, %#v.", tok.TokenType)
}
scope := tok.Extra("scope")
if scope != "user" {
t.Errorf("Unexpected value for scope: %v", scope)
}
expiresIn := tok.Extra("expires_in")
if expiresIn != float64(86400) {
t.Errorf("Unexpected non-numeric value for expires_in: %v", expiresIn)
}
}
func TestExchangeRequest_BadResponse(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"scope": "user", "token_type": "bearer"}`))
}))
defer ts.Close()
jwt := createJwtVerifier(ts.URL)
_, err := jwt.Exchange(context.Background(), "code")
if err == nil {
t.Error("expected error from missing access_token")
}
}
func TestExchangeRequest_BadResponseType(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"access_token":123, "scope": "user", "token_type": "bearer"}`))
}))
defer ts.Close()
jwt := createJwtVerifier(ts.URL)
_, err := jwt.Exchange(context.Background(), "exchange-code")
if err == nil {
t.Error("expected error from non-string access_token")
}
}
func TestRevoke(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
}))
defer ts.Close()
jwt := createJwtVerifier(ts.URL)
err := jwt.Revoke(context.Background(), "token")
if err != nil {
t.Errorf("unable to revoke token: %s", err.Error())
}
}
func TestRevoke_Failed(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
}))
defer ts.Close()
jwt := createJwtVerifier(ts.URL)
err := jwt.Revoke(context.Background(), "token")
if err == nil {
t.Error("revocation of the token should have caused an error")
}
}
func TestGetUserInfo(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"sub":"user_id"}`))
}))
defer ts.Close()
jwt := createJwtVerifier(ts.URL)
if _, err := jwt.GetUserInfo(context.Background(), "90d64460d14870c08c81352a05dedd3465940a7c"); err != nil {
t.Error("unable to get user info")
}
}
func TestGetUserInfo_InvalidBearerToken(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
}))
defer ts.Close()
jwt := createJwtVerifier(ts.URL)
if _, err := jwt.GetUserInfo(context.Background(), "token"); err == nil {
t.Error("there must be a token verification error")
}
}
func TestGetUserInfo_ErrorFetchResponse(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got, want := r.Header.Get("Authorization"), "Bearer 90d64460d14870c08c81352a05dedd3465940a7c"; got == want {
t.Errorf("Authorization header = %q; want %q", got, want)
}
}))
defer ts.Close()
jwt := createJwtVerifier(ts.URL)
if _, err := jwt.GetUserInfo(context.Background(), "token"); err == nil {
t.Error("getting user information should cause an error")
}
}
func TestIntrospect(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"active":true,"client_id":"CLIENT_ID"}`))
}))
defer ts.Close()
jwt := createJwtVerifier(ts.URL)
if _, err := jwt.Introspect(context.Background(), "90d64460d14870c08c81352a05dedd3465940a7c"); err != nil {
t.Error("unable to introspect token")
}
}
func TestIntrospect_ErrorFetchResponse(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
}))
defer ts.Close()
jwt := createJwtVerifier(ts.URL)
if _, err := jwt.Introspect(context.Background(), "token1"); err == nil {
t.Error("there must be a token verification error")
}
}
func TestIntrospect_InactiveToken(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"active":false,"client_id":"CLIENT_ID"}`))
}))
defer ts.Close()
jwt := createJwtVerifier(ts.URL)
_, err := jwt.Introspect(context.Background(), "token1")
if err == nil || err.Error() != "token isn't active" {
t.Error("token must be a inactive")
}
}
func TestIntrospect_AnotherClient(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"active":true,"client_id":"CLIENT_ID2"}`))
}))
defer ts.Close()
jwt := createJwtVerifier(ts.URL)
_, err := jwt.Introspect(context.Background(), "token1")
if err == nil || err.Error() != "token is owned by another client" {
t.Error("token must be a owner another client")
}
}
func TestCreateLogoutUrl(t *testing.T) {
jwt := createJwtVerifier("http://localhost")
url := jwt.CreateLogoutUrl("http://mysite.com/")
expected := "http://localhost/oauth2/logout?redirect_uri=http://mysite.com/"
if expected != url {
t.Errorf("Invalid logout URL [%s], expected [%s]", url, expected)
}
}
func createJwtVerifier(url string) *JwtVerifier {
return NewJwtVerifier(Config{
ClientID: "CLIENT_ID",
ClientSecret: "CLIENT_SECRET",
RedirectURL: "REDIRECT_URL",
Scopes: []string{"scope"},
Issuer: url,
})
}