-
Notifications
You must be signed in to change notification settings - Fork 0
/
IntegrationTests.cs
1670 lines (1279 loc) · 73.7 KB
/
IntegrationTests.cs
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
namespace Test;
public class IntegrationTests
: IClassFixture<WebApplicationFactory<Program>>
{
readonly ITestOutputHelper testOutput;
public IntegrationTests(
ITestOutputHelper testOutputHelper
)
{
this.testOutput = testOutputHelper;
}
static readonly string AuthApiPrefix = $"{API_PREFIX}/{nameof(AuthController).StripEnd("Controller")}";
/// <summary>
/// Test login admin works with username.
/// </summary>
[Fact]
public async Task ValidAdminLogin()
{
using var testFactory = new TestFactory();
await testFactory.InitAsync();
var client = testFactory.Client;
var config = testFactory.Services.GetRequiredService<IConfiguration>();
var adminUsername = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_UserName);
var adminPassword = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password);
// login with username
var loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminUsername,
Password = adminPassword
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
}
/// <summary>
/// Test login admin works with email.
/// </summary>
[Fact]
public async Task ValidAdminLoginWithEmail()
{
using var testFactory = new TestFactory();
await testFactory.InitAsync();
var client = testFactory.Client;
var config = testFactory.Services.GetRequiredService<IConfiguration>();
var adminEmail = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Email);
var adminPassword = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password);
// login with email
var loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminEmail,
Password = adminPassword
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
}
/// <summary>
/// Test admin current user works after valid username login
/// </summary>
[Fact]
public async Task ValidAdminCurrentUser()
{
using var testFactory = new TestFactory();
await testFactory.InitAsync();
var client = testFactory.Client;
var config = testFactory.Services.GetRequiredService<IConfiguration>();
var util = testFactory.Services.GetRequiredService<IUtilService>();
var adminUsername = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_UserName);
var adminEmail = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Email);
var adminPassword = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password);
var adminRoles = new List<string> { ROLE_admin };
// login with username
var loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminUsername,
Password = adminPassword
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
// retrieve current user
var currentUserRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.CurrentUser)}")).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, currentUserRes.StatusCode);
var currentUser = await currentUserRes.DeserializeAsync<CurrentUserResponseDto>(util);
Assert.NotNull(currentUser);
Assert.Equal(adminUsername, currentUser.UserName);
Assert.Equal(adminEmail, currentUser.Email);
Assert.Equal(adminRoles, currentUser.Roles);
}
/// <summary>
/// Test admin login with username and invalid password not succeeded.
/// </summary>
[Fact]
public async Task InvalidAdminLogin()
{
using var testFactory = new TestFactory();
await testFactory.InitAsync();
var client = testFactory.Client;
var config = testFactory.Services.GetRequiredService<IConfiguration>();
var adminUsername = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_UserName);
var adminPassword = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password) + "WRONG";
var loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminUsername,
Password = adminPassword
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.Unauthorized, loginRes.StatusCode);
}
/// <summary>
/// Test admin login with email and invalid password not succeeded.
/// </summary>
[Fact]
public async Task InvalidAdminLoginWithEmail()
{
using var testFactory = new TestFactory();
await testFactory.InitAsync();
var client = testFactory.Client;
var config = testFactory.Services.GetRequiredService<IConfiguration>();
var adminEmail = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Email);
var adminPassword = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password) + "WRONG";
var loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminEmail,
Password = adminPassword
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.Unauthorized, loginRes.StatusCode);
}
/// <summary>
/// States that access token not valid after expiration if refresh token already expired
/// </summary>
[Fact]
public async Task AccessTokenExpiration()
{
var accessTokenDuration = TimeSpan.FromSeconds(1);
var refreshTokenDuration = TimeSpan.FromSeconds(0); // disabled
using var testFactory = new TestFactory();
await testFactory.InitAsync();
var client = testFactory.Client;
var config = testFactory.Services.GetRequiredService<IConfiguration>();
config.SetConfigVar(CONFIG_KEY_JwtSettings_ClockSkewSeconds, "0");
config.SetConfigVar(CONFIG_KEY_JwtSettings_AccessTokenDurationSeconds, accessTokenDuration.TotalSeconds.ToString());
config.SetConfigVar(CONFIG_KEY_JwtSettings_RefreshTokenDurationSeconds, refreshTokenDuration.TotalSeconds.ToString());
var adminUsername = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_UserName);
var adminPassword = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password);
var loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminUsername,
Password = adminPassword
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
await Task.Delay(accessTokenDuration);
var currentUserRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.CurrentUser)}")).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.Unauthorized, currentUserRes.StatusCode);
}
/// <summary>
/// Renew access token when refresh token still valid.
/// </summary>
[Fact]
public async Task RenewAccessToken()
{
var accessTokenDuration = TimeSpan.FromSeconds(1);
var refreshTokenDuration = TimeSpan.FromSeconds(3);
using var testFactory = new TestFactory();
await testFactory.InitAsync();
var client = testFactory.Client;
var config = testFactory.Services.GetRequiredService<IConfiguration>();
config.SetConfigVar(CONFIG_KEY_JwtSettings_ClockSkewSeconds, "0");
config.SetConfigVar(CONFIG_KEY_JwtSettings_AccessTokenDurationSeconds, accessTokenDuration.TotalSeconds.ToString());
config.SetConfigVar(CONFIG_KEY_JwtSettings_RefreshTokenDurationSeconds, refreshTokenDuration.TotalSeconds.ToString());
var adminUsername = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_UserName);
var adminPassword = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password);
var loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminUsername,
Password = adminPassword
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
await Task.Delay(accessTokenDuration);
var currentUserRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.CurrentUser)}")).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, currentUserRes.StatusCode);
}
/// <summary>
/// Test refresh token can't be used twice because rotated.
/// </summary>
[Fact]
public async Task RotateRefreshToken()
{
var accessTokenDuration = TimeSpan.FromSeconds(1);
var refreshTokenDuration = TimeSpan.FromMinutes(10);
var refreshTokenRotationSkew = accessTokenDuration + TimeSpan.FromSeconds(1);
using var testFactory = new TestFactory();
await testFactory.InitAsync();
var client = testFactory.Client;
var config = testFactory.Services.GetRequiredService<IConfiguration>();
var logger = testFactory.Services.GetRequiredService<ILogger<IntegrationTests>>();
var dbContext = testFactory.Services.GetRequiredService<AppDbContext>();
config.SetConfigVar(CONFIG_KEY_JwtSettings_ClockSkewSeconds, "0");
config.SetConfigVar(CONFIG_KEY_JwtSettings_AccessTokenDurationSeconds,
accessTokenDuration.TotalSeconds.ToString());
config.SetConfigVar(CONFIG_KEY_JwtSettings_RefreshTokenDurationSeconds,
refreshTokenDuration.TotalSeconds.ToString());
config.SetConfigVar(CONFIG_KEY_JwtSettings_RefreshTokenRotationSkewSeconds,
refreshTokenRotationSkew.TotalSeconds.ToString());
var adminUsername = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_UserName);
var adminPassword = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password);
logger.LogTrace("Login");
var loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminUsername,
Password = adminPassword
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
var jwtCookies = loginRes.Headers.GetJwtCookiesFromResponse();
Assert.NotNull(jwtCookies.AccessToken);
var refreshToken1 = HttpUtility.UrlDecode(jwtCookies.RefreshToken);
Assert.NotNull(refreshToken1);
logger.LogTrace($"1) Wait access token expires ( refreshToken: {refreshToken1} )");
await Task.Delay(accessTokenDuration);
// access token now expired, then refresh token will be used and rotated in next call
var currentUserRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.CurrentUser)}")).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, currentUserRes.StatusCode);
jwtCookies = currentUserRes.Headers.GetJwtCookiesFromResponse();
Assert.NotNull(jwtCookies.AccessToken);
var refreshToken2 = HttpUtility.UrlDecode(jwtCookies.RefreshToken);
Assert.NotNull(refreshToken2);
logger.LogTrace($"2) Wait access token expires ( refreshToken: {refreshToken2} )");
// old refreshToken still valid because rotated + skew still valid
await Task.Delay(accessTokenDuration);
currentUserRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.CurrentUser)}")).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, currentUserRes.StatusCode);
jwtCookies = currentUserRes.Headers.GetJwtCookiesFromResponse();
Assert.NotNull(jwtCookies.AccessToken);
var refreshToken3 = HttpUtility.UrlDecode(jwtCookies.RefreshToken);
Assert.NotNull(refreshToken3);
logger.LogTrace($"3) Wait access token expires ( refreshToken: {refreshToken3} )");
await Task.Delay(accessTokenDuration);
currentUserRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.CurrentUser)}")).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.Unauthorized, currentUserRes.StatusCode);
logger.LogTrace("Login");
loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminUsername,
Password = adminPassword
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
jwtCookies = loginRes.Headers.GetJwtCookiesFromResponse();
Assert.NotNull(jwtCookies.AccessToken);
var refreshToken4 = HttpUtility.UrlDecode(jwtCookies.RefreshToken);
Assert.NotNull(refreshToken4);
// refreshToken4 differs from refreshToken3 because rotate+skew window now expired
logger.LogTrace($"final refresh token {refreshToken4}");
Assert.NotEqual(refreshToken4, refreshToken3);
// the login executed a refresh token maintenance that removed not more valid refreshToken3
var refreshTokensCount = dbContext.UserRefreshTokens.Count(w => w.UserName == "admin");
logger.LogTrace($"refresh tokens in db {refreshTokensCount}");
Assert.Equal(1, refreshTokensCount);
}
/// <summary>
/// Renewal of refresh token allow to slide the expiration.
/// </summary>
[Fact]
public async Task RewnewRefreshToken()
{
var accessTokenDuration = TimeSpan.FromSeconds(1);
var refreshTokenDuration = TimeSpan.FromSeconds(3);
var refreshTokenRotationSkew = accessTokenDuration + TimeSpan.FromSeconds(1);
using var testFactory = new TestFactory();
await testFactory.InitAsync();
var client = testFactory.Client;
var config = testFactory.Services.GetRequiredService<IConfiguration>();
var logger = testFactory.Services.GetRequiredService<ILogger<IntegrationTests>>();
var dbContext = testFactory.Services.GetRequiredService<AppDbContext>();
var util = testFactory.Services.GetRequiredService<IUtilService>();
config.SetConfigVar(CONFIG_KEY_JwtSettings_ClockSkewSeconds, "0");
config.SetConfigVar(CONFIG_KEY_JwtSettings_AccessTokenDurationSeconds,
accessTokenDuration.TotalSeconds.ToString());
config.SetConfigVar(CONFIG_KEY_JwtSettings_RefreshTokenDurationSeconds,
refreshTokenDuration.TotalSeconds.ToString());
config.SetConfigVar(CONFIG_KEY_JwtSettings_RefreshTokenRotationSkewSeconds,
refreshTokenRotationSkew.TotalSeconds.ToString());
var adminUsername = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_UserName);
var adminPassword = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password);
logger.LogTrace("Login");
var loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminUsername,
Password = adminPassword
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
var loginResObj = await loginRes.DeserializeAsync<LoginResponseDto>(util);
Assert.NotNull(loginResObj);
var toWait = loginResObj.RefreshTokenExpiration - DateTimeOffset.UtcNow - TimeSpan.FromSeconds(1);
logger.LogTrace($"1) Wait ( {toWait.TotalSeconds} sec ) refresh token about to expire");
await Task.Delay(toWait);
// refresh token still valid, now slide a new refresh token through renew refresh token
var renewRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.RenewRefreshToken)}")).ApplySetCookies(client);
toWait = refreshTokenDuration - TimeSpan.FromSeconds(1);
logger.LogTrace($"2) Wait ( {toWait.TotalSeconds} sec ) refresh token about to expire");
await Task.Delay(toWait);
// refresh token still valid because renewed
var currentUserRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.CurrentUser)}")).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, currentUserRes.StatusCode);
// last renew
logger.LogTrace($"3) Last renew refresh token");
renewRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.RenewRefreshToken)}")).ApplySetCookies(client);
// leave refresh expire using the refresh token provided configuration duration
toWait = refreshTokenDuration + TimeSpan.FromSeconds(1);
logger.LogTrace($"4) Wait ( {toWait.TotalSeconds} sec ) refresh token to expire");
await Task.Delay(toWait);
currentUserRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.CurrentUser)}")).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.Unauthorized, currentUserRes.StatusCode);
}
/// <summary>
/// Invalid renew refresh token on disabled user.
/// </summary>
[Fact]
public async Task InvalidRenewRefreshTokenOnDisabledUser()
{
var accessTokenDuration = TimeSpan.FromSeconds(1);
var refreshTokenDuration = TimeSpan.FromSeconds(3);
var refreshTokenRotationSkew = accessTokenDuration + TimeSpan.FromSeconds(1);
using var adminTestFactory = new TestFactory();
await adminTestFactory.InitAsync();
var adminClient = adminTestFactory.Client;
var adminConfig = adminTestFactory.Services.GetRequiredService<IConfiguration>();
var logger = adminTestFactory.Services.GetRequiredService<ILogger<IntegrationTests>>();
var util = adminTestFactory.Services.GetRequiredService<IUtilService>();
//
using var userTestFactory = new TestFactory();
await userTestFactory.InitAsync(dropDb: false);
var userClient = userTestFactory.Client;
var userConfig = userTestFactory.Services.GetRequiredService<IConfiguration>();
userConfig.SetConfigVar(CONFIG_KEY_JwtSettings_ClockSkewSeconds, "0");
userConfig.SetConfigVar(CONFIG_KEY_JwtSettings_AccessTokenDurationSeconds,
accessTokenDuration.TotalSeconds.ToString());
userConfig.SetConfigVar(CONFIG_KEY_JwtSettings_RefreshTokenDurationSeconds,
refreshTokenDuration.TotalSeconds.ToString());
userConfig.SetConfigVar(CONFIG_KEY_JwtSettings_RefreshTokenRotationSkewSeconds,
refreshTokenRotationSkew.TotalSeconds.ToString());
//
var adminUsername = adminConfig.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_UserName);
var adminPassword = adminConfig.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password);
var loginRes = (await adminClient.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminUsername,
Password = adminPassword
})).ApplySetCookies(adminClient);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
// create normal user
var normalUsername = "normalUsername";
var normalEmail = "normal@test.com";
var normalPassword = "normalPass1!";
var normalRoles = new[] { ROLE_normal };
var editUserRes = (await adminClient.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.EditUser)}/", new EditUserRequestDto
{
EditUsername = normalUsername,
EditEmail = normalEmail,
EditPassword = normalPassword,
EditRoles = normalRoles
})).ApplySetCookies(adminClient);
Assert.Equal(HttpStatusCode.OK, editUserRes.StatusCode);
// login normal user
loginRes = (await userClient.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = normalUsername,
Password = normalPassword
})).ApplySetCookies(userClient);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
var loginResObj = await loginRes.DeserializeAsync<LoginResponseDto>(util);
Assert.NotNull(loginResObj);
var toWait = loginResObj.RefreshTokenExpiration - DateTimeOffset.UtcNow - TimeSpan.FromSeconds(1);
logger.LogTrace($"1) Wait ( {toWait.TotalSeconds} sec ) refresh token about to expire");
await Task.Delay(toWait);
// refresh token still valid, now slide a new refresh token through renew refresh token
var renewRes = (await userClient.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.RenewRefreshToken)}")).ApplySetCookies(userClient);
var currentUserRes = (await userClient.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.CurrentUser)}")).ApplySetCookies(userClient);
Assert.Equal(HttpStatusCode.OK, currentUserRes.StatusCode);
// disable user
logger.LogTrace($"2) admin disable the user");
editUserRes = (await adminClient.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.EditUser)}/", new EditUserRequestDto
{
ExistingUsername = normalUsername,
EditDisabled = true
})).ApplySetCookies(adminClient);
toWait = refreshTokenDuration - TimeSpan.FromSeconds(1);
logger.LogTrace($"2) Wait ( {toWait.TotalSeconds} sec ) refresh token about to expire");
await Task.Delay(toWait);
// refresh token not valid because user disabled meanwhile
currentUserRes = (await userClient.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.CurrentUser)}")).ApplySetCookies(userClient);
Assert.Equal(HttpStatusCode.Unauthorized, currentUserRes.StatusCode);
}
/// <summary>
/// Refresh token removed from db after logout.
/// </summary>
[Fact]
public async Task RefreshTokenAfterLogout()
{
using var testFactory = new TestFactory();
await testFactory.InitAsync();
var client = testFactory.Client;
var config = testFactory.Services.GetRequiredService<IConfiguration>();
var logger = testFactory.Services.GetRequiredService<ILogger<IntegrationTests>>();
var dbContext = testFactory.Services.GetRequiredService<AppDbContext>();
var adminUsername = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_UserName);
var adminPassword = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password);
logger.LogTrace("Login");
var loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminUsername,
Password = adminPassword
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
var refreshTokensCount = dbContext.UserRefreshTokens.Count(w => w.UserName == "admin");
logger.LogTrace($"refresh tokens in db {refreshTokensCount}");
Assert.Equal(1, refreshTokensCount);
logger.LogTrace("Logout");
var logoutRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.Logout)}")).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, logoutRes.StatusCode);
refreshTokensCount = dbContext.UserRefreshTokens.Count(w => w.UserName == "admin");
logger.LogTrace($"refresh tokens in db {refreshTokensCount}");
Assert.Equal(0, refreshTokensCount);
}
/// <summary>
/// Invalid refresh token on disabled user.
/// </summary>
[Fact]
public async Task InvalidRefreshTokenOnDisabledUser()
{
var accessTokenDuration = TimeSpan.FromSeconds(1);
using var adminTestFactory = new TestFactory();
await adminTestFactory.InitAsync();
var adminClient = adminTestFactory.Client;
var adminConfig = adminTestFactory.Services.GetRequiredService<IConfiguration>();
var logger = adminTestFactory.Services.GetRequiredService<ILogger<IntegrationTests>>();
adminConfig.SetConfigVar(CONFIG_KEY_JwtSettings_ClockSkewSeconds, "0");
adminConfig.SetConfigVar(CONFIG_KEY_JwtSettings_AccessTokenDurationSeconds, accessTokenDuration.TotalSeconds.ToString());
//
using var userTestFactory = new TestFactory();
await userTestFactory.InitAsync(dropDb: false);
var userClient = userTestFactory.Client;
var userConfig = userTestFactory.Services.GetRequiredService<IConfiguration>();
userConfig.SetConfigVar(CONFIG_KEY_JwtSettings_ClockSkewSeconds, "0");
userConfig.SetConfigVar(CONFIG_KEY_JwtSettings_AccessTokenDurationSeconds, accessTokenDuration.TotalSeconds.ToString());
//
var adminUsername = adminConfig.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_UserName);
var adminPassword = adminConfig.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password);
var loginRes = (await adminClient.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminUsername,
Password = adminPassword
})).ApplySetCookies(adminClient);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
// create normal user
var normalUsername = "normalUsername";
var normalEmail = "normal@test.com";
var normalPassword = "normalPass1!";
var normalRoles = new[] { ROLE_normal };
var editUserRes = (await adminClient.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.EditUser)}/", new EditUserRequestDto
{
EditUsername = normalUsername,
EditEmail = normalEmail,
EditPassword = normalPassword,
EditRoles = normalRoles
})).ApplySetCookies(adminClient);
Assert.Equal(HttpStatusCode.OK, editUserRes.StatusCode);
// login normal user
loginRes = (await userClient.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = normalUsername,
Password = normalPassword
})).ApplySetCookies(userClient);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
logger.LogTrace($"waiting user access token expire");
await Task.Delay(accessTokenDuration);
// disable user
editUserRes = (await adminClient.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.EditUser)}/", new EditUserRequestDto
{
ExistingUsername = normalUsername,
EditDisabled = true
})).ApplySetCookies(adminClient);
// test current user can't use refresh token
var currentUserRes = (await userClient.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.CurrentUser)}"))
.ApplySetCookies(userClient);
Assert.Equal(HttpStatusCode.Unauthorized, currentUserRes.StatusCode);
}
/// <summary>
/// Test access token valid from, to params.
/// </summary>
[Fact]
public async Task AccessTokenValidFromTo()
{
var DRIFT = TimeSpan.FromSeconds(1);
using var testFactory = new TestFactory();
await testFactory.InitAsync();
var client = testFactory.Client;
var config = testFactory.Services.GetRequiredService<IConfiguration>();
var accessTokenDuration = TimeSpan.FromSeconds(config.GetConfigVar<double>(CONFIG_KEY_JwtSettings_AccessTokenDurationSeconds));
var adminUsername = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_UserName);
var adminPassword = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password);
var loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminUsername,
Password = adminPassword
})).ApplySetCookies(client);
var dtStart = DateTimeOffset.UtcNow;
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
var jwtCookies = loginRes.Headers.GetJwtCookiesFromResponse();
Assert.NotNull(jwtCookies.AccessToken);
var jwt = DecodeToJwtSecurityToken(jwtCookies.AccessToken);
Assert.NotNull(jwt);
// jwt issued >= req start
Assert.True(jwt.IssuedAt + DRIFT >= dtStart);
// jet valid from >= req start
Assert.True(jwt.ValidFrom + DRIFT >= dtStart);
// jwt from + duration = to
Assert.Equal(jwt.ValidFrom + accessTokenDuration, jwt.ValidTo);
}
/// <summary>
/// Test access token invalid with fake token.
/// </summary>
[Fact]
public async Task AccessTokenInvalidWithFake()
{
using var testFactory = new TestFactory();
await testFactory.InitAsync();
var client = testFactory.Client;
var config = testFactory.Services.GetRequiredService<IConfiguration>();
var adminUsername = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_UserName);
var adminPassword = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password);
var loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminUsername,
Password = adminPassword
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
var jwtCookies = loginRes.Headers.GetJwtCookiesFromResponse();
Assert.NotNull(jwtCookies.AccessToken);
var fakeAccessToken = GenerateFakeAccessToken(config, jwtCookies.AccessToken);
client.SetCookie(WEB_CookieName_XAccessToken, fakeAccessToken);
var currentUserRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.CurrentUser)}")).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.Unauthorized, currentUserRes.StatusCode);
}
/// <summary>
/// Test logout.
/// </summary>
[Fact]
public async Task UnauthorizedAfterLogout()
{
using var testFactory = new TestFactory();
await testFactory.InitAsync();
var client = testFactory.Client;
var config = testFactory.Services.GetRequiredService<IConfiguration>();
var adminUsername = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_UserName);
var adminPassword = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password);
var loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminUsername,
Password = adminPassword
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
var logoutRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.Logout)}")).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, logoutRes.StatusCode);
var currentUserRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.CurrentUser)}")).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.Unauthorized, currentUserRes.StatusCode);
}
/// <summary>
/// Use ListUsers to test the default admin user seed executed.
/// </summary>
[Fact]
public async Task SeedDefaultAdmin()
{
using var testFactory = new TestFactory();
await testFactory.InitAsync();
var client = testFactory.Client;
var config = testFactory.Services.GetRequiredService<IConfiguration>();
var util = testFactory.Services.GetRequiredService<IUtilService>();
var adminUsername = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_UserName);
var adminPassword = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password);
var loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminUsername,
Password = adminPassword
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
var listUsersRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.ListUsers)}/")).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, listUsersRes.StatusCode);
var listUsers = await listUsersRes.DeserializeAsync<List<UserListItemResponseDto>>(util);
Assert.NotNull(listUsers);
Assert.Single(listUsers);
Assert.Equal(config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_UserName), listUsers[0].UserName);
Assert.Equal(config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Email), listUsers[0].Email);
Assert.Equal(new List<string> { ROLE_admin }, listUsers[0].Roles);
}
/// <summary>
/// Create admin, advanced user, normal user and verify permissions association.
/// </summary>
[Fact]
public async Task VerifyRolePermissionAssociations()
{
using var testFactory = new TestFactory();
await testFactory.InitAsync();
var client = testFactory.Client;
var config = testFactory.Services.GetRequiredService<IConfiguration>();
var util = testFactory.Services.GetRequiredService<IUtilService>();
var adminUsername = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_UserName);
var adminPassword = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password);
var loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminUsername,
Password = adminPassword
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
// create advanced user
var advancedUsername = "advancedUsername";
var advancedEmail = "advanced@test.com";
var advancedPassword = "advancedPass1!";
var advancedRoles = new[] { ROLE_advanced };
var editUserRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.EditUser)}/", new EditUserRequestDto
{
EditUsername = advancedUsername,
EditEmail = advancedEmail,
EditPassword = advancedPassword,
EditRoles = advancedRoles
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, editUserRes.StatusCode);
// create normal user
var normalUsername = "normalUsername";
var normalEmail = "normal@test.com";
var normalPassword = "normalPass1!";
var normalRoles = new[] { ROLE_normal };
editUserRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.EditUser)}/", new EditUserRequestDto
{
EditUsername = normalUsername,
EditEmail = normalEmail,
EditPassword = normalPassword,
EditRoles = normalRoles
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, editUserRes.StatusCode);
ExpectedPermissionsNfo[] expectedPermissions = {
new ExpectedPermissionsNfo(adminUsername, adminPassword,
PermissionsFromRoles(new HashSet<string>() { ROLE_admin }).ToArray()),
new ExpectedPermissionsNfo(advancedUsername, advancedPassword,
PermissionsFromRoles(new HashSet<string>() { ROLE_advanced }).ToArray()),
new ExpectedPermissionsNfo(normalUsername, normalPassword,
PermissionsFromRoles(new HashSet<string>() { ROLE_normal }).ToArray()),
};
foreach (var permnfo in expectedPermissions)
{
// logout
var logoutRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.Logout)}")).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, logoutRes.StatusCode);
// login
loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = permnfo.username,
Password = permnfo.password
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
// current user
var currentUserRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.CurrentUser)}")).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, currentUserRes.StatusCode);
var currentUser = await currentUserRes.DeserializeAsync<CurrentUserResponseDto>(util);
Assert.NotNull(currentUser);
Assert.Equal(permnfo.permissions, currentUser.Permissions);
}
}
/// <summary>
/// Test <see cref="AuthController.EditUser"/>
/// </summary>
[Fact]
public async Task TestEditUser()
{
using var testFactory = new TestFactory();
await testFactory.InitAsync();
var client = testFactory.Client;
var config = testFactory.Services.GetRequiredService<IConfiguration>();
var util = testFactory.Services.GetRequiredService<IUtilService>();
var logger = testFactory.Services.GetRequiredService<ILogger<IntegrationTests>>();
var adminUsername = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_UserName);
var adminEmail = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Email);
var adminPassword = config.GetConfigVar<string>(CONFIG_KEY_SeedUsers_Admin_Password);
var adminRoles = new[] { ROLE_admin };
var loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = adminUsername,
Password = adminPassword
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
// create advanced user
var advancedUsername = "advancedUsername";
var advancedEmail = "advanced@test.com";
var advancedPassword = "advancedPass1!";
var advancedRoles = new[] { ROLE_advanced };
var editUserRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.EditUser)}/", new EditUserRequestDto
{
EditUsername = advancedUsername,
EditEmail = advancedEmail,
EditPassword = advancedPassword,
EditRoles = advancedRoles
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, editUserRes.StatusCode);
// create normal user
var normalUsername = "normalUsername";
var normalEmail = "normal@test.com";
var normalPassword = "normalPass1!";
var normalRoles = new[] { ROLE_normal };
editUserRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.EditUser)}/", new EditUserRequestDto
{
EditUsername = normalUsername,
EditEmail = normalEmail,
EditPassword = normalPassword,
EditRoles = normalRoles
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, editUserRes.StatusCode);
UserCredentialNfo[] userCredentials = {
new UserCredentialNfo(adminUsername, adminEmail, adminPassword, "adm"),
new UserCredentialNfo(advancedUsername, advancedEmail, advancedPassword, "adv"),
new UserCredentialNfo(normalUsername, normalEmail, normalPassword, "nrm"),
};
// other users created by admin
var otherAdminUsername = $"adm_create_admin";
var otherAdvancedUsername = $"adm_create_advanced";
var otherNormalUsername = $"adm_create_normal";
foreach (var _userCredential in userCredentials.WithIndex())
{
var userCredential = _userCredential.item;
var userCredentialIdx = _userCredential.idx;
logger.LogTrace($"Testing (1th) {userCredential.username} capabilities");
// logout
var logoutRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.Logout)}")).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, logoutRes.StatusCode);
// login
loginRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.Login)}", new LoginRequestDto
{
UsernameOrEmail = userCredential.username,
Password = userCredential.password
})).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, loginRes.StatusCode);
// current user
var currentUserRes = (await client.GetAsync($"{AuthApiPrefix}/{nameof(AuthController.CurrentUser)}")).ApplySetCookies(client);
Assert.Equal(HttpStatusCode.OK, currentUserRes.StatusCode);
var currentUser = await currentUserRes.DeserializeAsync<CurrentUserResponseDto>(util);
Assert.NotNull(currentUser);
//------------------------------------------------------------------
logger.LogTrace($" {UserPermission.CreateAdminUser}");
{
editUserRes = (await client.PostAsJsonAsync($"{AuthApiPrefix}/{nameof(AuthController.EditUser)}/", new EditUserRequestDto
{
EditUsername = $"{userCredential.testPrefix}_create_admin",
EditEmail = $"{userCredential.testPrefix}_admin@test.com",