-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth_test.go
258 lines (224 loc) · 8.19 KB
/
auth_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
package auth
import (
"github.com/dgrijalva/jwt-go"
"net/http"
"reflect"
"testing"
)
// issued at GMT Friday, 30. November 2018 10:00:40 (1543572040), valid until GMT: Friday, 30. November 2018 10:01:58 (1543572118)
var expiredToken = "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NDM1NzIxMTgsImlhdCI6MTU0MzU3MjA0MCwiaXNzIjoiZmx5aW5nIGR1dGNobWFuIiwic3ViIjoic3VwZXJhZG1pbiIsIm5hbWUiOiJNYXJ0eSBNY0ZseSIsImF1dGhvcml0aWVzIjpbeyJyb2xlIjoiYWRtaW4iLCJvcmdVbml0cyI6W3siaWQiOjIxLCJuYW1lIjoib3JnIHVuaXQifV19XX0.ZuvEdONZiyhB2oFA8VF5bV8hCzD6Ctng43TcMFuu30vD3rcd5iR_ePQiQb-npW93SEyd7YlBjnjIA2QTnOGEvg"
// issued at GMT Friday, 30. November 2018 10:00:40 (1543572040), valid until GMT Monday, 30. November 2099 10:08:04 (4099716484)
var tokenValidUntil2099 = "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjQwOTk3MTY0ODQsImlhdCI6MTU0MzU3MjA0MCwiaXNzIjoiZmx5aW5nIGR1dGNobWFuIiwic3ViIjoic3VwZXJhZG1pbiIsIm5hbWUiOiJNYXJ0eSBNY0ZseSIsInVzZXJuYW1lIjoibWFydHkiLCJhdXRob3JpdGllcyI6W3sicm9sZSI6ImFkbWluIiwib3JnVW5pdHMiOlt7ImlkIjoyMSwibmFtZSI6Im9yZyB1bml0In1dfV19.m7FA3NTVn9OLvsszRApmFb2k4xZoTVIC-RUbwE1zBaDO9V4mUjFDwNHxBqNarkVi18Qq5iAsmFAEcenWuFwCHQ"
var issuedAt = int64(1543572040)
var expiresShortlyAfter = int64(1543572118)
var expires2099 = int64(4099716484)
/**
Should convert valid token and return no error.
*/
func TestToAuthenticationWithValidToken(t *testing.T) {
authService := New(Config{
JWTPrivateKey: []byte("privatesigningpassowrd"),
})
expectedAuthentication := &Authentication{
ExpiresAt: expires2099,
Issuer: "flying dutchman",
Subject: "superadmin",
IssuedAt: issuedAt,
Name: "Marty McFly",
Username: "marty",
Authorities: []GrantedAuthority{
{
Role: "admin",
OrgUnits: []OrganizationalUnit{
{Name: "org unit", Id: 21},
},
},
},
}
authentication, error := authService.FromCookie(&http.Cookie{
Value: tokenValidUntil2099,
})
if !reflect.DeepEqual(authentication, expectedAuthentication) {
t.Fail()
}
if error != nil {
t.Fail()
}
}
func TestToValidJWTTokenCookie(t *testing.T) {
authService := New(Config{
JWTPrivateKey: []byte("privatesigningpassowrd"),
})
authentication := Authentication{
ExpiresAt: expires2099,
Issuer: "flying dutchman",
Subject: "superadmin",
IssuedAt: issuedAt,
Name: "Marty McFly",
Username: "marty",
Authorities: []GrantedAuthority{
{
Role: "admin",
OrgUnits: []OrganizationalUnit{
{Name: "org unit", Id: 21},
},
},
},
}
cookie := authService.ToJWTCookie(&authentication)
if cookie.Value != tokenValidUntil2099 {
t.Fail()
}
}
func TestToJWTTokenCookie(t *testing.T) {
// given
authService := New(Config{
JWTPrivateKey: []byte("privatesigningpassowrd"),
})
authentication := Authentication{
ExpiresAt: expiresShortlyAfter,
Issuer: "flying dutchman",
Subject: "superadmin",
IssuedAt: issuedAt,
Name: "Marty McFly",
Authorities: []GrantedAuthority{
{
Role: "admin",
OrgUnits: []OrganizationalUnit{
{Name: "org unit", Id: 21},
},
},
},
}
// when
cookie := authService.ToJWTCookie(&authentication)
// then
if cookie.Value != expiredToken {
t.Fail()
}
}
func TestToAuthenticationWithExpiredAndTamperedToken(t *testing.T) {
// actual Password in the to be tested token is different, simulating a tampered token
authService := New(Config{
JWTPrivateKey: []byte("somethingSomething"),
})
authentication, err := authService.FromCookie(&http.Cookie{
Value: expiredToken,
})
// authentication should be nil, since token is invalid
if authentication != nil {
t.Fail()
}
valError := err.(*jwt.ValidationError)
// should contain signature invalid error
if valError.Errors&jwt.ValidationErrorSignatureInvalid == 0 {
// if not, fail test
t.Fail()
}
}
/**
Should be possible to interpret expired token.
*/
func TestToAuthentication(t *testing.T) {
// given
authService := New(Config{
JWTPrivateKey: []byte("privatesigningpassowrd"),
})
expectedAuthentication := &Authentication{
ExpiresAt: expiresShortlyAfter,
Issuer: "flying dutchman",
Subject: "superadmin",
IssuedAt: issuedAt,
Name: "Marty McFly",
Authorities: []GrantedAuthority{
{
Role: "admin",
OrgUnits: []OrganizationalUnit{
{Name: "org unit", Id: 21},
},
},
},
}
// when
authentication, validationError := authService.FromCookie(&http.Cookie{
Value: expiredToken,
})
// then expected is equal to actual
if !reflect.DeepEqual(authentication, expectedAuthentication) {
t.Errorf("Expected authentication is different than one retrieved from cookie")
}
// and error is token expired
if validationError, ok := validationError.(*jwt.ValidationError); ok {
if validationError.Errors != jwt.ValidationErrorExpired {
t.Errorf("Token should only have error 'expired'")
}
} else {
t.Errorf("Token should be expired")
}
}
func TestRefreshAuthentication(t *testing.T) {
authService := New(Config{
JWTCookieName: "JWT",
MaxRenewalTime: 9999999999999,
})
authentication := &Authentication{
Username: "[email protected]",
ExpiresAt: expiresShortlyAfter,
Issuer: "flying dutchman app",
Subject: "superadmin",
IssuedAt: issuedAt,
Name: "Marty McFly",
Authorities: []GrantedAuthority{
{
Role: "admin",
OrgUnits: []OrganizationalUnit{
{Name: "org unit", Id: 21},
},
},
},
}
refreshAuth, _ := authService.RefreshAuthentication(authentication)
// fail if expiracy is equal between original and refreshed token
if refreshAuth.ExpiresAt <= authentication.ExpiresAt {
t.Errorf("ExpiresAt should have changed its value to a time in future")
}
// fail if issuedAt changed; we want it to be like it was when it first was generated, so that we may
// keep track of old issued tokens and prevent them being refreshed after a max refresh time has been reached
if refreshAuth.IssuedAt != authentication.IssuedAt {
t.Errorf("issuedAt has a new value; should have remained the same")
}
// fail if other properties are not equal. we expect that all properties have been copied as is, without modification
if refreshAuth.Username != authentication.Username ||
refreshAuth.Subject != authentication.Subject ||
refreshAuth.Name != authentication.Name ||
!reflect.DeepEqual(refreshAuth.Authorities, authentication.Authorities) {
t.Errorf("Remaining fields should have remained unaltered")
}
}
func TestRefreshAuthenticationFailureForMaxTimeReached(t *testing.T) {
authService := New(Config{
JWTCookieName: "JWT",
MaxRenewalTime: 5, //5 seconds, force max renewal error
})
authentication := &Authentication{
Username: "[email protected]",
ExpiresAt: expiresShortlyAfter,
Issuer: "flying dutchman app",
Subject: "superadmin",
IssuedAt: issuedAt,
Name: "Marty McFly",
Authorities: []GrantedAuthority{
{
Role: "admin",
OrgUnits: []OrganizationalUnit{
{Name: "org unit", Id: 21},
},
},
},
}
_, err := authService.RefreshAuthentication(authentication)
if authErr, castSuccess := err.(*Error); !castSuccess ||
authErr.ErrorCode != MaxRefreshTimeReached {
t.Errorf("Should have returned an error when refreshing; error code should be MaxRefreshTimeReached")
}
}