-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTokenCacheTests.cs
More file actions
1523 lines (1251 loc) · 67.7 KB
/
Copy pathTokenCacheTests.cs
File metadata and controls
1523 lines (1251 loc) · 67.7 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
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Castle.Core.Internal;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.AppConfig;
using Microsoft.Identity.Client.Cache;
using Microsoft.Identity.Client.Cache.Items;
using Microsoft.Identity.Client.Core;
using Microsoft.Identity.Client.Instance;
using Microsoft.Identity.Client.Instance.Discovery;
using Microsoft.Identity.Client.Internal;
using Microsoft.Identity.Client.Internal.Requests;
using Microsoft.Identity.Client.OAuth2;
using Microsoft.Identity.Client.PlatformsCommon.Interfaces;
using Microsoft.Identity.Client.TelemetryCore.Internal.Events;
using Microsoft.Identity.Client.Utils;
using Microsoft.Identity.Test.Common;
using Microsoft.Identity.Test.Common.Core.Helpers;
using Microsoft.Identity.Test.Common.Core.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NSubstitute;
namespace Microsoft.Identity.Test.Unit.CacheTests
{
[TestClass]
public class TokenCacheTests : TestBase
{
public static long ValidExpiresIn = 3600;
public static long ValidExtendedExpiresIn = 7200;
private string _clientInfo;
private string _homeAccountId;
[TestInitialize]
public override void TestInitialize()
{
_clientInfo = MockHelpers.CreateClientInfo();
_homeAccountId = ClientInfo.CreateFromJson(_clientInfo).ToAccountIdentifier();
base.TestInitialize();
}
[TestMethod]
[DataRow(true, true, true)]
[DataRow(true, false, false)]
[DataRow(false, true, false)]
public async Task WithLegacyCacheCompatibilityTest_Async(
bool enableLegacyCacheCompatibility,
bool serializeCache,
bool expectToCallAdalLegacyCache)
{
using (MockHttpManager mockHttpManager = new MockHttpManager())
{
// Arrange
var legacyCachePersistence = Substitute.For<ILegacyCachePersistence>();
mockHttpManager.AddInstanceDiscoveryMockHandler();
var serviceBundle = TestCommon.CreateServiceBundleWithCustomHttpManager(mockHttpManager, isLegacyCacheEnabled: enableLegacyCacheCompatibility);
var requestContext = new RequestContext(serviceBundle, Guid.NewGuid(), null);
var response = TestConstants.CreateMsalTokenResponse();
ITokenCacheInternal cache = new TokenCache(serviceBundle, false, legacyCachePersistence);
if (serializeCache) // no point in invoking the Legacy ADAL cache if you're only keeping it memory
{
cache.SetBeforeAccess((_) => { });
}
var requestParams = TestCommon.CreateAuthenticationRequestParameters(serviceBundle);
requestParams.AuthorityManager = new AuthorityManager(
requestContext,
Authority.CreateAuthorityWithTenant(
requestParams.AuthorityInfo,
TestConstants.Utid));
requestParams.Account = new Account(TestConstants.s_userIdentifier, $"1{TestConstants.DisplayableId}", TestConstants.ProductionPrefNetworkEnvironment);
// Act
await cache.FindRefreshTokenAsync(requestParams).ConfigureAwait(true);
await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(true);
await cache.GetAccountsAsync(requestParams).ConfigureAwait(true);
await cache.RemoveAccountAsync(requestParams.Account, requestParams).ConfigureAwait(true);
// Assert
if (expectToCallAdalLegacyCache)
{
legacyCachePersistence.ReceivedWithAnyArgs().LoadCache();
legacyCachePersistence.ReceivedWithAnyArgs().WriteCache(Arg.Any<byte[]>());
}
else
{
legacyCachePersistence.DidNotReceiveWithAnyArgs().LoadCache();
legacyCachePersistence.DidNotReceiveWithAnyArgs().WriteCache(Arg.Any<byte[]>());
}
}
}
[TestMethod]
[DataRow(true)]
[DataRow(false)]
public async Task WithMultiCloudSupportTest_Async(
bool multiCloudSupportEnabled)
{
// Arrange
using (MockHttpManager mockHttpManager = new MockHttpManager())
{
mockHttpManager.AddInstanceDiscoveryMockHandler();
var serviceBundle = TestCommon.CreateServiceBundleWithCustomHttpManager(
mockHttpManager,
isMultiCloudSupportEnabled: multiCloudSupportEnabled);
var requestContext = new RequestContext(serviceBundle, Guid.NewGuid(), null);
var response = TestConstants.CreateMsalTokenResponse();
ITokenCacheInternal cache = new TokenCache(serviceBundle, false);
var requestParams = TestCommon.CreateAuthenticationRequestParameters(serviceBundle);
requestParams.AuthorityManager = new AuthorityManager(
requestContext,
Authority.CreateAuthorityWithTenant(
requestParams.AuthorityInfo,
TestConstants.Utid));
requestParams.Account = new Account(TestConstants.s_userIdentifier, $"1{TestConstants.DisplayableId}", TestConstants.ProductionPrefNetworkEnvironment);
var res = await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(true);
IEnumerable<IAccount> accounts = await cache.GetAccountsAsync(requestParams).ConfigureAwait(true);
Assert.IsNotNull(accounts);
Assert.IsNotNull(accounts.Single());
MsalRefreshTokenCacheItem refreshToken = await cache.FindRefreshTokenAsync(requestParams).ConfigureAwait(true);
Assert.IsNotNull(refreshToken);
MsalIdTokenCacheItem idToken = cache.GetIdTokenCacheItem(res.Item1);
Assert.IsNotNull(idToken);
await cache.RemoveAccountAsync(requestParams.Account, requestParams).ConfigureAwait(true);
accounts = await cache.GetAccountsAsync(requestParams).ConfigureAwait(true);
Assert.IsNotNull(accounts);
Assert.IsTrue(accounts.IsNullOrEmpty());
}
}
[TestMethod]
public void GetExactScopesMatchedAccessTokenTest()
{
using (var harness = CreateTestHarness())
{
ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle, false);
var atItem = TokenCacheHelper.CreateAccessTokenItem();
cache.Accessor.SaveAccessToken(atItem);
var item = cache.FindAccessTokenAsync(
harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityTestTenant,
TestConstants.s_scope,
cache,
account: TestConstants.s_user)).Result;
Assert.IsNotNull(item);
}
}
[TestMethod]
public void GetSubsetScopesMatchedAccessTokenTest()
{
using (var harness = CreateTestHarness())
{
ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle, false);
var atItem = TokenCacheHelper.CreateAccessTokenItem("r1/scope1 r1/scope2");
cache.Accessor.SaveAccessToken(atItem);
var param = harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityTestTenant,
new SortedSet<string>(),
cache,
account: TestConstants.s_user);
param.Scope.Add("r1/scope1");
var item = cache.FindAccessTokenAsync(param).Result;
Assert.IsNotNull(item);
}
}
[TestMethod]
[WorkItem(1548)] //https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/1548
public void TokenCacheHitTest()
{
VerifyAccessTokenIsFound("openid profile user.read", new[] { "User.Read" });
VerifyAccessTokenIsFound("openid profile User.Read", new[] { "User.Read", "offline_access" });
VerifyAccessTokenIsFound("openid profile User.Read", new[] { "offline_access" });
VerifyAccessTokenIsFound("non_graph_scope", new[] { "profile" });
VerifyAccessTokenIsFound("non_graph_scope", new[] { "openid" });
VerifyAccessTokenIsFound("non_graph_scope", new[] { "offline_access" });
VerifyAccessTokenIsFound("non_graph_scope", new[] { "OFFline_access" });
VerifyAccessTokenIsFound("non_graph_scope", new[] { "non_graph_scope", "offline_access" }); // regression
VerifyAccessTokenIsFound("non_graph_scope", new[] { "offline_access", "profile" });
VerifyAccessTokenIsFound("non_graph_scope", new[] { "offline_access", "profile", "openid" });
VerifyAccessTokenIsFound("non_graph_scope", new[] { "non_graph_scope", "offline_access", "profile", "openid" });
VerifyAccessTokenIsFound("", new string[0]);
VerifyAccessTokenIsFound(null, new string[0]);
VerifyAccessTokenIsFound("non_graph_scope", new string[0]);
VerifyAccessTokenIsFound("openid profile User.Read", new string[0]);
VerifyAccessTokenIsFound("openid profile User.Read", new[] { "User.Read" });
VerifyAccessTokenIsFound("", new[] { "" });
VerifyAccessTokenIsNotFound("openid profile user.read", new[] { "non_graph_scope" });
VerifyAccessTokenIsNotFound("openid profile user.read", new[] { "email" });
VerifyAccessTokenIsNotFound("openid profile user.read", new[] { "user.read", "email" });
}
private void VerifyAccessTokenIsFound(string cachedAtScopes, string[] queryScopes, bool expectFind = true)
{
using (var harness = CreateTestHarness())
{
ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle, false);
var atItem = new MsalAccessTokenCacheItem(
TestConstants.ProductionPrefNetworkEnvironment,
TestConstants.ClientId,
cachedAtScopes,
TestConstants.Utid,
null,
DateTimeOffset.UtcNow,
DateTimeOffset.UtcNow + TimeSpan.FromHours(1),
DateTimeOffset.UtcNow + TimeSpan.FromHours(2),
_clientInfo,
_homeAccountId);
cache.Accessor.SaveAccessToken(atItem);
var param = harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityTestTenant,
queryScopes,
cache,
account: TestConstants.s_user);
var item = cache.FindAccessTokenAsync(param).Result;
if (expectFind == true)
Assert.IsNotNull(item);
else
Assert.IsNull(item);
}
}
private void VerifyAccessTokenIsNotFound(string cachedAtScopes, string[] queryScopes)
{
VerifyAccessTokenIsFound(cachedAtScopes, queryScopes, false);
}
[TestMethod]
public void GetIntersectedScopesMatchedAccessTokenTest()
{
using (var harness = CreateTestHarness())
{
ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle, false);
var atItem = TokenCacheHelper.CreateAccessTokenItem();
cache.Accessor.SaveAccessToken(atItem);
var param = harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityHomeTenant,
new SortedSet<string>(),
cache,
account: new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null));
param.Scope.Add(TestConstants.s_scope.First());
param.Scope.Add("non-existent-scopes");
var item = cache.FindAccessTokenAsync(param).Result;
// intersected scopes are not returned.
Assert.IsNull(item);
}
}
[TestMethod]
public void AccessToken_WithRefresh_FromMsalResponseJson()
{
// Arrange
string json = TestConstants.TokenResponseJson;
json = JsonTestUtils.AddKeyValue(json, "refresh_in", "1800");
var tokenResponse = JsonHelper.DeserializeFromJson<MsalTokenResponse>(json);
var homeAccountId = ClientInfo.CreateFromJson(tokenResponse.ClientInfo).ToAccountIdentifier();
// Act
MsalAccessTokenCacheItem at = new MsalAccessTokenCacheItem(
TestConstants.ProductionPrefNetworkEnvironment,
TestConstants.ClientId,
tokenResponse,
TestConstants.TenantId,
homeAccountId);
// Assert
Assert.AreEqual(1800, tokenResponse.RefreshIn);
Assert.AreEqual(tokenResponse.TokenType, at.TokenType);
Assert.IsNull(at.KeyId);
Assert.IsTrue(at.RefreshOn.HasValue);
CoreAssert.IsWithinRange(
at.RefreshOn.Value,
(at.CachedAt + TimeSpan.FromSeconds(1800)),
TimeSpan.FromSeconds(Constants.DefaultJitterRangeInSeconds));
}
[TestMethod]
public void AccessToken_WithKidAndType_FromMsalResponseJson()
{
// Arrange
string json = TestConstants.TokenResponseJson;
json = JsonTestUtils.AddKeyValue(json, StorageJsonKeys.TokenType, "pop");
var tokenResponse = JsonHelper.DeserializeFromJson<MsalTokenResponse>(json);
var homeAccountId = ClientInfo.CreateFromJson(tokenResponse.ClientInfo).ToAccountIdentifier();
// Act
MsalAccessTokenCacheItem at = new MsalAccessTokenCacheItem(
TestConstants.ProductionPrefNetworkEnvironment,
TestConstants.ClientId,
tokenResponse,
TestConstants.TenantId,
homeAccountId,
keyId: "kid1");
// Assert
Assert.AreEqual("kid1", at.KeyId);
CoreAssert.AreEqual(tokenResponse.TokenType, at.TokenType, "pop");
}
[TestMethod]
public void AccessToken_WithNoRefresh_FromMsalResponseJson()
{
// Arrange
string json = TestConstants.TokenResponseJson;
var tokenResponse = JsonHelper.DeserializeFromJson<MsalTokenResponse>(json);
var homeAccountId = ClientInfo.CreateFromJson(tokenResponse.ClientInfo).ToAccountIdentifier();
// Act
MsalAccessTokenCacheItem at = new MsalAccessTokenCacheItem(
TestConstants.ProductionPrefNetworkEnvironment,
TestConstants.ClientId,
tokenResponse,
homeAccountId,
TestConstants.TenantId);
// Assert
Assert.IsNull(tokenResponse.RefreshIn);
Assert.IsFalse(at.RefreshOn.HasValue);
}
[TestMethod]
public void GetExpiredAccessTokenTest()
{
using (var harness = CreateTestHarness())
{
ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle, false);
var atItem = new MsalAccessTokenCacheItem(
TestConstants.ProductionPrefNetworkEnvironment,
TestConstants.ClientId,
TestConstants.s_scope.AsSingleString(),
TestConstants.Utid,
null,
DateTimeOffset.UtcNow - TimeSpan.FromMinutes(30),
DateTimeOffset.UtcNow,
DateTimeOffset.UtcNow + TimeSpan.FromHours(2),
_clientInfo,
_homeAccountId);
cache.Accessor.SaveAccessToken(atItem);
var param = harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityTestTenant,
new SortedSet<string>(),
cache,
account: new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null));
Assert.IsNull(cache.FindAccessTokenAsync(param).Result);
}
}
[TestMethod]
// Regression test for https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/1806
public void GetInvalidExpirationAccessTokenTest()
{
using (var harness = CreateTestHarness())
{
ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle, false);
var atItem = new MsalAccessTokenCacheItem(
TestConstants.ProductionPrefNetworkEnvironment,
TestConstants.ClientId,
TestConstants.s_scope.AsSingleString(),
TestConstants.Utid,
null,
cachedAt: DateTimeOffset.UtcNow,
expiresOn: new DateTimeOffset(
DateTime.UtcNow +
TimeSpan.FromDays(TokenCache.ExpirationTooLongInDays) +
TimeSpan.FromMinutes(5)),
extendedExpiresOn: DateTimeOffset.UtcNow,
_clientInfo,
_homeAccountId);
atItem.Secret = atItem.CacheKey;
cache.Accessor.SaveAccessToken(atItem);
var param = harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityTestTenant,
new SortedSet<string>(),
cache,
account: new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null));
Assert.IsNull(cache.FindAccessTokenAsync(param).Result);
}
}
[TestMethod]
public void GetExpiredAccessToken_WithExtendedExpireStillValid_Test()
{
using (var harness = CreateTestHarness(isExtendedTokenLifetimeEnabled: true))
{
ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle, false);
var atItem = new MsalAccessTokenCacheItem(
TestConstants.ProductionPrefNetworkEnvironment,
TestConstants.ClientId,
TestConstants.s_scope.AsSingleString(),
TestConstants.Utid,
null,
new DateTimeOffset(DateTime.UtcNow),
new DateTimeOffset(DateTime.UtcNow),
new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(2)),
_clientInfo,
_homeAccountId);
atItem.Secret = atItem.CacheKey;
cache.Accessor.SaveAccessToken(atItem);
var param = harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityTestTenant,
new SortedSet<string>(),
cache,
account: new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null));
var cacheItem = cache.FindAccessTokenAsync(param).Result;
Assert.IsNotNull(cacheItem);
Assert.AreEqual(atItem.CacheKey, cacheItem.CacheKey);
Assert.IsTrue(cacheItem.IsExtendedLifeTimeToken);
}
}
[TestMethod]
[TestCategory(TestCategories.TokenCacheTests)]
public void GetAccessTokenExpiryInRangeTest()
{
using (var harness = CreateTestHarness())
{
ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle, false);
var atItem = new MsalAccessTokenCacheItem(
TestConstants.ProductionPrefNetworkEnvironment,
TestConstants.ClientId,
TestConstants.s_scope.AsSingleString(),
TestConstants.Utid,
"",
new DateTimeOffset(DateTime.UtcNow),
new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromMinutes(4)),
new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(2)),
_clientInfo,
_homeAccountId);
atItem.Secret = atItem.CacheKey;
cache.Accessor.SaveAccessToken(atItem);
var param = harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityTestTenant,
new SortedSet<string>(),
cache,
account: new Account(TestConstants.s_userIdentifier, TestConstants.DisplayableId, null));
Assert.IsNull(cache.FindAccessTokenAsync(param).Result);
}
}
[TestMethod]
// regression for https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/3130
public void ExpiryNoTokens()
{
using (var harness = CreateTestHarness())
{
// Arrange
ITokenCacheInternal appTokenCache = new TokenCache(harness.ServiceBundle, true);
ITokenCacheInternal userTokenCache = new TokenCache(harness.ServiceBundle, false);
var logger = Substitute.For<ILoggerAdapter>();
// Act
var appAccessorExpiration = TokenCache.CalculateSuggestedCacheExpiry(appTokenCache.Accessor, logger);
var userAccessorExpiration = TokenCache.CalculateSuggestedCacheExpiry(userTokenCache.Accessor, logger);
// Assert
Assert.IsNull(appAccessorExpiration);
Assert.IsNull(userAccessorExpiration);
Assert.IsFalse(appTokenCache.Accessor.HasAccessOrRefreshTokens());
Assert.IsFalse(userTokenCache.Accessor.HasAccessOrRefreshTokens());
}
}
[TestMethod]
// regression for https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/3130
public void TokensCloseToExpiry_NoTokens()
{
using (var harness = CreateTestHarness())
{
// Arrange
ITokenCacheInternal appTokenCache = new TokenCache(harness.ServiceBundle, true);
ITokenCacheInternal userTokenCache = new TokenCache(harness.ServiceBundle, false);
var logger = Substitute.For<ILoggerAdapter>();
var t1 = TokenCacheHelper.CreateAccessTokenItem(isExpired: true);
var t2 = TokenCacheHelper.CreateAccessTokenItem(isExpired: true);
// token that expires in less than 5 min and is seen as expired by msal
var t3 = TokenCacheHelper.CreateAccessTokenItem(exiresIn: Constants.AccessTokenExpirationBuffer - TimeSpan.FromSeconds(1));
appTokenCache.Accessor.SaveAccessToken(t1);
appTokenCache.Accessor.SaveAccessToken(t2);
appTokenCache.Accessor.SaveAccessToken(t3);
userTokenCache.Accessor.SaveAccessToken(t1);
userTokenCache.Accessor.SaveAccessToken(t2);
userTokenCache.Accessor.SaveAccessToken(t3);
// Act
var appAccessorExpiration = TokenCache.CalculateSuggestedCacheExpiry(appTokenCache.Accessor, logger);
var userAccessorExpiration = TokenCache.CalculateSuggestedCacheExpiry(userTokenCache.Accessor, logger);
// Assert
Assert.IsNull(appAccessorExpiration);
Assert.IsNull(userAccessorExpiration);
Assert.IsFalse(appTokenCache.Accessor.HasAccessOrRefreshTokens());
Assert.IsFalse(userTokenCache.Accessor.HasAccessOrRefreshTokens());
// Arrange - token that is not seen as expired
var t4 = TokenCacheHelper.CreateAccessTokenItem(exiresIn: Constants.AccessTokenExpirationBuffer + TimeSpan.FromMinutes(1));
appTokenCache.Accessor.SaveAccessToken(t4);
userTokenCache.Accessor.SaveAccessToken(t4);
// Act
appAccessorExpiration = TokenCache.CalculateSuggestedCacheExpiry(appTokenCache.Accessor, logger);
userAccessorExpiration = TokenCache.CalculateSuggestedCacheExpiry(userTokenCache.Accessor, logger);
// Assert
CoreAssert.IsWithinRange(t4.ExpiresOn, appAccessorExpiration.Value, TimeSpan.FromSeconds(3));
CoreAssert.IsWithinRange(t4.ExpiresOn, userAccessorExpiration.Value, TimeSpan.FromSeconds(3));
Assert.IsTrue(appTokenCache.Accessor.HasAccessOrRefreshTokens());
Assert.IsTrue(userTokenCache.Accessor.HasAccessOrRefreshTokens());
}
}
[TestMethod]
[TestCategory(TestCategories.TokenCacheTests)]
public void GetRefreshTokenTest()
{
using (var harness = CreateTestHarness())
{
ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle, false);
var rtItem = new MsalRefreshTokenCacheItem(
TestConstants.ProductionPrefNetworkEnvironment,
TestConstants.ClientId,
"someRT",
_clientInfo,
null,
_homeAccountId);
cache.Accessor.SaveRefreshToken(rtItem);
var authParams = harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityTestTenant,
TestConstants.s_scope,
cache,
account: TestConstants.s_user);
Assert.IsNotNull(cache.FindRefreshTokenAsync(authParams));
// RT is stored by environment, client id and userIdentifier as index.
// any change to authority (within same environment), uniqueid and displyableid will not
// change the outcome of cache look up.
Assert.IsNotNull(cache.FindRefreshTokenAsync(
harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityHomeTenant + "more",
TestConstants.s_scope,
cache,
account: TestConstants.s_user)));
}
}
[TestMethod]
public void GetRefreshTokenDifferentEnvironmentTest()
{
using (var harness = CreateTestHarness())
{
ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle, false);
var rtItem = new MsalRefreshTokenCacheItem(
TestConstants.SovereignNetworkEnvironmentDE,
TestConstants.ClientId,
"someRT",
_clientInfo,
null,
_homeAccountId);
cache.Accessor.SaveRefreshToken(rtItem);
var authParams = harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityTestTenant,
TestConstants.s_scope,
cache,
account: TestConstants.s_user);
var rt = cache.FindRefreshTokenAsync(authParams).Result;
Assert.IsNull(rt);
}
}
[TestMethod]
[TestCategory(TestCategories.TokenCacheTests)]
public async Task GetAppTokenFromCacheTestAsync()
{
using (var harness = CreateTestHarness())
{
ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle, true);
var atItem = new MsalAccessTokenCacheItem(
TestConstants.ProductionPrefNetworkEnvironment,
TestConstants.ClientId,
TestConstants.s_scope.AsSingleString(),
TestConstants.Utid,
null,
new DateTimeOffset(DateTime.UtcNow),
new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)),
new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExtendedExpiresIn)),
_clientInfo,
_homeAccountId);
string atKey = atItem.CacheKey;
atItem.Secret = atKey;
cache.Accessor.SaveAccessToken(atItem);
var authParams = harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityTestTenant,
TestConstants.s_scope,
cache,
apiId: ApiEvent.ApiIds.AcquireTokenForClient);
var cacheItem = await cache.FindAccessTokenAsync(authParams).ConfigureAwait(false);
Assert.IsNotNull(cacheItem);
Assert.AreEqual(atItem.CacheKey, cacheItem.CacheKey);
}
}
[TestMethod]
[TestCategory(TestCategories.TokenCacheTests)]
public async Task DoNotSaveRefreshTokenInAdalCacheForMsalB2CAuthorityTestAsync()
{
var appConfig = new ApplicationConfiguration(MsalClientType.ConfidentialClient)
{
ClientId = TestConstants.ClientId,
RedirectUri = TestConstants.RedirectUri,
Authority = Authority.CreateAuthority(TestConstants.B2CAuthority, false)
};
var serviceBundle = ServiceBundle.Create(appConfig);
ITokenCacheInternal cache = new TokenCache(serviceBundle, false);
MsalTokenResponse response = TestConstants.CreateMsalTokenResponse();
var authority = Authority.CreateAuthority(TestConstants.B2CAuthority);
authority = Authority.CreateAuthorityWithTenant(
authority.AuthorityInfo,
TestConstants.Utid);
var requestParams = TestCommon.CreateAuthenticationRequestParameters(
serviceBundle,
authority);
AddHostToInstanceCache(serviceBundle, TestConstants.ProductionPrefNetworkEnvironment);
await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false);
Assert.AreEqual(1, cache.Accessor.GetAllRefreshTokens().Count());
Assert.AreEqual(1, cache.Accessor.GetAllAccessTokens().Count());
IDictionary<AdalTokenCacheKey, AdalResultWrapper> dictionary =
AdalCacheOperations.Deserialize(serviceBundle.ApplicationLogger, cache.LegacyPersistence.LoadCache());
cache.LegacyPersistence.WriteCache(AdalCacheOperations.Serialize(serviceBundle.ApplicationLogger, dictionary));
// ADAL cache is empty because B2C scenario is only for MSAL
Assert.IsEmpty(dictionary);
}
[TestMethod]
[TestCategory(TestCategories.TokenCacheTests)]
public void GetAccessAndRefreshTokenNoUserAssertionInCacheTest()
{
using (var harness = CreateTestHarness())
{
ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle, false);
var atItem = new MsalAccessTokenCacheItem(
TestConstants.ProductionPrefNetworkEnvironment,
TestConstants.ClientId,
TestConstants.s_scope.AsSingleString(),
TestConstants.Utid,
null,
new DateTimeOffset(DateTime.UtcNow),
new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(1)),
new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(2)),
_clientInfo,
_homeAccountId);
// create key out of access token cache item and then
// set it as the value of the access token.
string atKey = atItem.CacheKey;
atItem.Secret = atKey;
cache.Accessor.SaveAccessToken(atItem);
var rtItem = new MsalRefreshTokenCacheItem(
TestConstants.ProductionPrefNetworkEnvironment,
TestConstants.ClientId,
null,
_clientInfo,
null,
_homeAccountId);
string rtKey = rtItem.CacheKey;
rtItem.Secret = rtKey;
cache.Accessor.SaveRefreshToken(rtItem);
var authParams = harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityTestTenant,
TestConstants.s_scope,
cache,
apiId: ApiEvent.ApiIds.AcquireTokenOnBehalfOf);
authParams.UserAssertion = new UserAssertion(
harness.ServiceBundle.PlatformProxy.CryptographyManager.CreateBase64UrlEncodedSha256Hash(atKey));
var item = cache.FindAccessTokenAsync(authParams).Result;
// cache lookup should fail because there was no userassertion hash in the matched
// token cache item.
Assert.IsNull(item);
}
}
[TestMethod]
[TestCategory(TestCategories.TokenCacheTests)]
public void GetAccessAndRefreshTokenUserAssertionMismatchInCacheTest()
{
using (var harness = CreateTestHarness())
{
ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle, false);
string assertion = harness.ServiceBundle.PlatformProxy.CryptographyManager.CreateBase64UrlEncodedSha256Hash("T");
var atItem = new MsalAccessTokenCacheItem(
TestConstants.ProductionPrefNetworkEnvironment,
TestConstants.ClientId,
TestConstants.s_scope.AsSingleString(),
TestConstants.Utid,
null,
new DateTimeOffset(DateTime.UtcNow),
new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(1)),
new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(2)),
_clientInfo,
_homeAccountId,
oboCacheKey: assertion);
cache.Accessor.SaveAccessToken(atItem);
var rtItem = new MsalRefreshTokenCacheItem(
TestConstants.ProductionPrefNetworkEnvironment,
TestConstants.ClientId,
null,
_clientInfo,
null,
_homeAccountId);
string rtKey = rtItem.CacheKey;
rtItem.Secret = rtKey;
rtItem.OboCacheKey = assertion;
cache.Accessor.SaveRefreshToken(rtItem);
var authParams = harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityTestTenant,
TestConstants.s_scope,
cache,
apiId: ApiEvent.ApiIds.AcquireTokenOnBehalfOf);
authParams.UserAssertion = new UserAssertion(atItem.OboCacheKey + "-random");
var itemAT = cache.FindAccessTokenAsync(authParams).Result;
var itemRT = cache.FindRefreshTokenAsync(authParams).Result;
// cache lookup should fail because there was user assertion hash did not match the one
// stored in token cache item.
Assert.IsNull(itemAT);
Assert.IsNull(itemRT);
}
}
[TestMethod]
[TestCategory(TestCategories.TokenCacheTests)]
public void GetAccessAndRefreshTokenMatchedUserAssertionInCacheTest()
{
using (var harness = CreateTestHarness())
{
ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle, false);
string assertionHash = harness.ServiceBundle.PlatformProxy.CryptographyManager.CreateBase64UrlEncodedSha256Hash("T");
var atItem = new MsalAccessTokenCacheItem(
TestConstants.ProductionPrefNetworkEnvironment,
TestConstants.ClientId,
TestConstants.s_scope.AsSingleString(),
TestConstants.Utid,
null,
new DateTimeOffset(DateTime.UtcNow),
new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(1)),
new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromHours(2)),
_clientInfo,
_homeAccountId,
oboCacheKey: assertionHash);
cache.Accessor.SaveAccessToken(atItem);
var rtItem = new MsalRefreshTokenCacheItem(
TestConstants.ProductionPrefNetworkEnvironment,
TestConstants.ClientId,
null,
_clientInfo,
null,
_homeAccountId);
rtItem.OboCacheKey = assertionHash;
cache.Accessor.SaveRefreshToken(rtItem);
var authParams = harness.CreateAuthenticationRequestParameters(
TestConstants.AuthorityTestTenant,
TestConstants.s_scope,
cache,
apiId: ApiEvent.ApiIds.AcquireTokenOnBehalfOf,
account: new Account(_homeAccountId, null, TestConstants.ProductionPrefNetworkEnvironment));
authParams.UserAssertion = new UserAssertion("T");
((TokenCache)cache).AfterAccess = AfterAccessNoChangeNotification;
var itemAT = cache.FindAccessTokenAsync(authParams).Result;
var itemRT = cache.FindRefreshTokenAsync(authParams).Result;
Assert.IsNotNull(itemAT);
Assert.IsNotNull(itemRT);
}
}
[TestMethod]
[TestCategory(TestCategories.TokenCacheTests)]
public async Task SaveAccessAndRefreshTokenWithEmptyCacheTestAsync()
{
var serviceBundle = TestCommon.CreateDefaultServiceBundle();
ITokenCacheInternal cache = new TokenCache(serviceBundle, false);
MsalTokenResponse response = TestConstants.CreateMsalTokenResponse();
var requestParams = TestCommon.CreateAuthenticationRequestParameters(serviceBundle);
requestParams.AuthorityManager = new AuthorityManager(
requestParams.RequestContext,
Authority.CreateAuthorityWithTenant(
requestParams.AuthorityInfo,
TestConstants.Utid));
AddHostToInstanceCache(serviceBundle, TestConstants.ProductionPrefNetworkEnvironment);
await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false);
cache.Accessor.AssertItemCount(
expectedAtCount: 1,
expectedRtCount: 1,
expectedAccountCount: 1,
expectedIdtCount: 1,
expectedAppMetadataCount: 1);
var metadata = cache.Accessor.GetAllAppMetadata().First();
Assert.AreEqual(TestConstants.ClientId, metadata.ClientId);
Assert.AreEqual(TestConstants.ProductionPrefNetworkEnvironment, metadata.Environment);
Assert.IsNull(metadata.FamilyId);
}
[TestMethod]
public async Task NoAppMetadata_WhenFociIsDisabledAsync()
{
using (var harness = CreateTestHarness())
{
// Arrange
var testFlags = Substitute.For<IFeatureFlags>();
testFlags.IsFociEnabled.Returns(false);
harness.ServiceBundle.PlatformProxy.SetFeatureFlags(testFlags);
ITokenCacheInternal cache = new TokenCache(harness.ServiceBundle, false);
MsalTokenResponse response = TestConstants.CreateMsalTokenResponse();
var requestParams = TestCommon.CreateAuthenticationRequestParameters(harness.ServiceBundle);
requestParams.AuthorityManager = new AuthorityManager(
requestParams.RequestContext,
Authority.CreateAuthorityWithTenant(
requestParams.AuthorityInfo,
TestConstants.Utid));
AddHostToInstanceCache(harness.ServiceBundle, TestConstants.ProductionPrefNetworkEnvironment);
// Act
await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false);
// Assert
cache.Accessor.AssertItemCount(
expectedAtCount: 1,
expectedRtCount: 1,
expectedAccountCount: 1,
expectedIdtCount: 1,
expectedAppMetadataCount: 0);
// Don't save RT as an FRT if FOCI is disabled
Assert.IsTrue(string.IsNullOrEmpty(cache.Accessor.GetAllRefreshTokens().First().FamilyId));
}
}
[TestMethod]
public async Task SaveMultipleAppmetadataAsync()
{
var serviceBundle = TestCommon.CreateDefaultServiceBundle();
ITokenCacheInternal cache = new TokenCache(serviceBundle, false);
MsalTokenResponse response = TestConstants.CreateMsalTokenResponse();
MsalTokenResponse response2 = TestConstants.CreateMsalTokenResponse();
response2.FamilyId = "1";
var requestParams = TestCommon.CreateAuthenticationRequestParameters(serviceBundle);
requestParams.AuthorityManager = new AuthorityManager(
requestParams.RequestContext,
Authority.CreateAuthorityWithTenant(
requestParams.AuthorityInfo,
TestConstants.Utid));
AddHostToInstanceCache(serviceBundle, TestConstants.ProductionPrefNetworkEnvironment);
await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false);
await cache.SaveTokenResponseAsync(requestParams, response2).ConfigureAwait(false);
cache.Accessor.AssertItemCount(
expectedAtCount: 1,
expectedRtCount: 2, // a normal RT and an FRT
expectedAccountCount: 1,
expectedIdtCount: 1,
expectedAppMetadataCount: 1);
var metadata = cache.Accessor.GetAllAppMetadata().First();
Assert.AreEqual(TestConstants.ClientId, metadata.ClientId);
Assert.AreEqual(TestConstants.ProductionPrefNetworkEnvironment, metadata.Environment);
Assert.AreEqual(TestConstants.FamilyId, metadata.FamilyId);
Assert.IsTrue(cache.Accessor.GetAllRefreshTokens().Any(rt => rt.FamilyId == "1"));
Assert.IsTrue(cache.Accessor.GetAllRefreshTokens().Any(rt => string.IsNullOrEmpty(rt.FamilyId)));
}
[TestMethod]
public void CreateFrtFromTokenResponse()
{
MsalTokenResponse response = TestConstants.CreateMsalTokenResponse();
response.FamilyId = "1";
var homeAccountId = ClientInfo.CreateFromJson(response.ClientInfo).ToAccountIdentifier();
var frt = new MsalRefreshTokenCacheItem(
"env",
TestConstants.ClientId,
response,
homeAccountId);
Assert.AreEqual("1", frt.FamilyId);
}
[TestMethod]
[TestCategory(TestCategories.TokenCacheTests)]
public async Task SaveAccessAndRefreshTokenWithMoreScopesTestAsync()
{
var serviceBundle = TestCommon.CreateDefaultServiceBundle();
ITokenCacheInternal cache = new TokenCache(serviceBundle, false);
MsalTokenResponse response = TestConstants.CreateMsalTokenResponse();
var requestParams = TestCommon.CreateAuthenticationRequestParameters(serviceBundle);
requestParams.AuthorityManager = new AuthorityManager(