-
Notifications
You must be signed in to change notification settings - Fork 403
Expand file tree
/
Copy pathTokenCache.ITokenCacheInternal.cs
More file actions
1512 lines (1291 loc) · 72.5 KB
/
TokenCache.ITokenCacheInternal.cs
File metadata and controls
1512 lines (1291 loc) · 72.5 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.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Identity.Client.ApiConfig.Parameters;
using Microsoft.Identity.Client.AuthScheme.Bearer;
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.TelemetryCore.Internal.Events;
using Microsoft.Identity.Client.TelemetryCore.TelemetryClient;
using Microsoft.Identity.Client.Utils;
namespace Microsoft.Identity.Client
{
/// <summary>
/// IMPORTANT: this class is performance critical; any changes must be benchmarked using Microsoft.Identity.Test.Performance.
/// More information about how to test and what data to look for is in https://aka.ms/msal-net-performance-testing.
/// </summary>
public sealed partial class TokenCache : ITokenCacheInternal
{
#region SaveTokenResponse
async Task<Tuple<MsalAccessTokenCacheItem, MsalIdTokenCacheItem, Account>> ITokenCacheInternal.SaveTokenResponseAsync(
AuthenticationRequestParameters requestParams,
MsalTokenResponse response)
{
var logger = requestParams.RequestContext.Logger;
response.Log(logger, LogLevel.Verbose);
MsalAccessTokenCacheItem msalAccessTokenCacheItem = null;
MsalRefreshTokenCacheItem msalRefreshTokenCacheItem = null;
MsalIdTokenCacheItem msalIdTokenCacheItem = null;
MsalAccountCacheItem msalAccountCacheItem = null;
IdToken idToken = IdToken.Parse(response.IdToken);
if (idToken == null)
{
logger.Info("[SaveTokenResponseAsync] ID Token not present in response. ");
}
var tenantId = TokenResponseHelper.GetTenantId(idToken, requestParams);
string username = TokenResponseHelper.GetUsernameFromIdToken(idToken);
string homeAccountId = TokenResponseHelper.GetHomeAccountId(requestParams, response, idToken);
string suggestedWebCacheKey = CacheKeyFactory.GetExternalCacheKeyFromResponse(requestParams, homeAccountId);
// token could be coming from a different cloud than the one configured
if (requestParams.AppConfig.MultiCloudSupportEnabled && !string.IsNullOrEmpty(response.AuthorityUrl))
{
var url = new Uri(response.AuthorityUrl);
requestParams.AuthorityManager = new AuthorityManager(
requestParams.RequestContext,
Authority.CreateAuthorityWithEnvironment(requestParams.Authority.AuthorityInfo, url.Host));
}
// Do a full instance discovery when saving tokens (if not cached),
// so that the PreferredNetwork environment is up to date.
InstanceDiscoveryMetadataEntry instanceDiscoveryMetadata =
await requestParams.AuthorityManager.GetInstanceDiscoveryEntryAsync().ConfigureAwait(false);
#region Create Cache Objects
if (!string.IsNullOrEmpty(response.AccessToken))
{
msalAccessTokenCacheItem =
new MsalAccessTokenCacheItem(
instanceDiscoveryMetadata.PreferredCache,
requestParams.AppConfig.ClientId,
response,
tenantId,
homeAccountId,
requestParams.AuthenticationScheme.KeyId,
CacheKeyFactory.GetOboKey(requestParams.LongRunningOboCacheKey, requestParams.UserAssertion),
requestParams.PersistedCacheParameters,
requestParams.CacheKeyComponents);
}
if (!string.IsNullOrEmpty(response.RefreshToken))
{
Debug.Assert(
requestParams.ApiId != ApiEvent.ApiIds.AcquireTokenForClient,
"client_credentials flow should not receive a refresh token");
Debug.Assert(
(requestParams.ApiId != ApiEvent.ApiIds.AcquireTokenForSystemAssignedManagedIdentity ||
requestParams.ApiId != ApiEvent.ApiIds.AcquireTokenForUserAssignedManagedIdentity),
"Managed identity flow should not receive a refresh token");
msalRefreshTokenCacheItem = new MsalRefreshTokenCacheItem(
instanceDiscoveryMetadata.PreferredCache,
requestParams.AppConfig.ClientId,
response,
homeAccountId)
{
OboCacheKey = CacheKeyFactory.GetOboKey(requestParams.LongRunningOboCacheKey, requestParams.UserAssertion),
};
if (!_featureFlags.IsFociEnabled)
{
msalRefreshTokenCacheItem.FamilyId = null;
}
}
Account account = null;
if (idToken != null)
{
Debug.Assert(
requestParams.ApiId != ApiEvent.ApiIds.AcquireTokenForClient,
"client_credentials flow should not receive an ID token");
Debug.Assert(
(requestParams.ApiId != ApiEvent.ApiIds.AcquireTokenForSystemAssignedManagedIdentity ||
requestParams.ApiId != ApiEvent.ApiIds.AcquireTokenForUserAssignedManagedIdentity),
"Managed identity flow should not receive an ID token");
msalIdTokenCacheItem = new MsalIdTokenCacheItem(
instanceDiscoveryMetadata.PreferredCache,
requestParams.AppConfig.ClientId,
response,
tenantId,
homeAccountId);
Dictionary<string, string> wamAccountIds = TokenResponseHelper.GetWamAccountIds(requestParams, response);
string accountSource = requestParams.ApiId == ApiEvent.ApiIds.AcquireTokenByDeviceCode ? "device_code_flow" : null;
msalAccountCacheItem = new MsalAccountCacheItem(
instanceDiscoveryMetadata.PreferredCache,
response.ClientInfo,
homeAccountId,
accountSource,
idToken,
username,
tenantId,
wamAccountIds);
// Add the newly obtained id token to the list of profiles.
IDictionary<string, TenantProfile> tenantProfiles = null;
if (msalIdTokenCacheItem.TenantId != null)
{
if (CacheOptions.IsDisabledFor(ServiceBundle.Config.AccessorOptions))
{
// When the internal cache is disabled, skip GetTenantProfilesAsync (which reads
// from Accessor) and instead seed a fresh dict with just the current profile.
tenantProfiles = new Dictionary<string, TenantProfile>
{
[msalIdTokenCacheItem.TenantId] = new TenantProfile(msalIdTokenCacheItem)
};
}
else
{
tenantProfiles = await GetTenantProfilesAsync(requestParams, homeAccountId).ConfigureAwait(false);
if (tenantProfiles != null)
{
tenantProfiles[msalIdTokenCacheItem.TenantId] = new TenantProfile(msalIdTokenCacheItem);
}
}
}
account = new Account(
homeAccountId,
username,
instanceDiscoveryMetadata.PreferredNetwork,
accountSource,
wamAccountIds,
tenantProfiles?.Values);
}
#endregion
if (CacheOptions.IsDisabledFor(ServiceBundle.Config.AccessorOptions))
{
logger.Verbose(() => "[SaveTokenResponseAsync] Internal cache is disabled (CacheOptions.DisableInternalCacheOptions). Skipping all cache writes.");
return Tuple.Create(msalAccessTokenCacheItem, msalIdTokenCacheItem, account);
}
logger.Verbose(() => $"[SaveTokenResponseAsync] Entering token cache semaphore. Count {_semaphoreSlim.GetCurrentCountLogMessage()}.");
await _semaphoreSlim.WaitAsync(requestParams.RequestContext.UserCancellationToken).ConfigureAwait(false);
logger.Verbose(() => "[SaveTokenResponseAsync] Entered token cache semaphore. ");
ITokenCacheInternal tokenCacheInternal = this;
try
{
try
{
if (tokenCacheInternal.IsAppSubscribedToSerializationEvents())
{
var args = new TokenCacheNotificationArgs(
tokenCache: this,
clientId: ClientId,
account: account,
hasStateChanged: true,
tokenCacheInternal.IsApplicationCache,
suggestedCacheKey: suggestedWebCacheKey,
hasTokens: tokenCacheInternal.HasTokensNoLocks(),
suggestedCacheExpiry: null,
cancellationToken: requestParams.RequestContext.UserCancellationToken,
correlationId: requestParams.RequestContext.CorrelationId,
requestScopes: requestParams.Scope,
requestTenantId: requestParams.AuthorityManager.OriginalAuthority.TenantId,
identityLogger: requestParams.RequestContext.Logger.IdentityLogger,
piiLoggingEnabled: requestParams.RequestContext.Logger.PiiLoggingEnabled);
var measuredResultDuration = await StopwatchService.MeasureCodeBlockAsync(async () =>
{
await tokenCacheInternal.OnBeforeAccessAsync(args).ConfigureAwait(false);
await tokenCacheInternal.OnBeforeWriteAsync(args).ConfigureAwait(false);
}).ConfigureAwait(false);
requestParams.RequestContext.ApiEvent.DurationInCacheInMs += measuredResultDuration.Milliseconds;
}
// Don't cache access tokens from broker
if (ShouldCacheAccessToken(msalAccessTokenCacheItem, response.TokenSource))
{
logger.Info("[SaveTokenResponseAsync] Saving AT in cache and removing overlapping ATs...");
DeleteAccessTokensWithIntersectingScopes(
requestParams,
instanceDiscoveryMetadata.Aliases,
tenantId,
msalAccessTokenCacheItem.ScopeSet,
msalAccessTokenCacheItem.HomeAccountId,
msalAccessTokenCacheItem.TokenType,
msalAccessTokenCacheItem.AdditionalCacheKeyComponents);
Accessor.SaveAccessToken(msalAccessTokenCacheItem);
}
if (idToken != null)
{
logger.Info("[SaveTokenResponseAsync] Saving Id Token and Account in cache ...");
Accessor.SaveIdToken(msalIdTokenCacheItem);
MergeWamAccountIds(msalAccountCacheItem);
Accessor.SaveAccount(msalAccountCacheItem);
}
// if server returns the refresh token back, save it in the cache.
if (msalRefreshTokenCacheItem != null)
{
logger.Info("[SaveTokenResponseAsync] Saving RT in cache...");
Accessor.SaveRefreshToken(msalRefreshTokenCacheItem);
}
UpdateAppMetadata(
requestParams.AppConfig.ClientId,
instanceDiscoveryMetadata.PreferredCache,
response.FamilyId);
SaveToLegacyAdalCache(
requestParams,
response,
msalRefreshTokenCacheItem,
msalIdTokenCacheItem,
tenantId,
instanceDiscoveryMetadata);
}
finally
{
if (tokenCacheInternal.IsAppSubscribedToSerializationEvents())
{
DateTimeOffset? cacheExpiry = CalculateSuggestedCacheExpiry(Accessor, logger);
var args = new TokenCacheNotificationArgs(
tokenCache: this,
clientId: ClientId,
account: account,
hasStateChanged: true,
tokenCacheInternal.IsApplicationCache,
suggestedCacheKey: suggestedWebCacheKey,
hasTokens: tokenCacheInternal.HasTokensNoLocks(),
suggestedCacheExpiry: cacheExpiry,
cancellationToken: requestParams.RequestContext.UserCancellationToken,
correlationId: requestParams.RequestContext.CorrelationId,
requestScopes: requestParams.Scope,
requestTenantId: requestParams.AuthorityManager.OriginalAuthority.TenantId,
identityLogger: requestParams.RequestContext.Logger.IdentityLogger,
piiLoggingEnabled: requestParams.RequestContext.Logger.PiiLoggingEnabled);
var measuredTimeDuration = await tokenCacheInternal.OnAfterAccessAsync(args).MeasureAsync().ConfigureAwait(false);
requestParams.RequestContext.ApiEvent.DurationInCacheInMs += measuredTimeDuration.Milliseconds;
LogCacheContents(requestParams);
}
}
return Tuple.Create(msalAccessTokenCacheItem, msalIdTokenCacheItem, account);
}
finally
{
_semaphoreSlim.Release();
logger.Verbose(() => "[SaveTokenResponseAsync] Released token cache semaphore. ");
}
}
private static bool ShouldCacheAccessToken(MsalAccessTokenCacheItem msalAccessTokenCacheItem, TokenSource tokenSource)
{
#if iOS
return msalAccessTokenCacheItem != null;
#else
return msalAccessTokenCacheItem != null && tokenSource != TokenSource.Broker;
#endif
}
//This method pulls all of the access and refresh tokens from the cache and can therefore be very impactful on performance.
//This will run on a background thread to mitigate this.
private void LogCacheContents(AuthenticationRequestParameters requestParameters)
{
if (requestParameters.RequestContext.Logger.IsLoggingEnabled(LogLevel.Verbose))
{
var accessTokenCacheItems = Accessor.GetAllAccessTokens();
var refreshTokenCacheItems = Accessor.GetAllRefreshTokens();
var accessTokenCacheItemsSubset = accessTokenCacheItems.Take(10).ToList();
var refreshTokenCacheItemsSubset = refreshTokenCacheItems.Take(10).ToList();
StringBuilder tokenCacheKeyLog = new StringBuilder();
tokenCacheKeyLog.AppendLine($"Total number of access tokens in the cache: {accessTokenCacheItems.Count}");
tokenCacheKeyLog.AppendLine($"Total number of refresh tokens in the cache: {refreshTokenCacheItems.Count}");
tokenCacheKeyLog.AppendLine($"First {accessTokenCacheItemsSubset.Count} access token cache keys:");
foreach (var cacheItem in accessTokenCacheItemsSubset)
{
tokenCacheKeyLog.AppendLine($"AT Cache Key: {cacheItem.ToLogString(requestParameters.RequestContext.Logger.PiiLoggingEnabled)}");
}
tokenCacheKeyLog.AppendLine($"First {refreshTokenCacheItemsSubset.Count} refresh token cache keys:");
foreach (var cacheItem in refreshTokenCacheItemsSubset)
{
tokenCacheKeyLog.AppendLine($"RT Cache Key: {cacheItem.ToLogString(requestParameters.RequestContext.Logger.PiiLoggingEnabled)}");
}
requestParameters.RequestContext.Logger.Verbose(() => tokenCacheKeyLog.ToString());
}
}
private bool IsLegacyAdalCacheEnabled(AuthenticationRequestParameters requestParams)
{
if (requestParams.IsClientCredentialRequest)
{
// client_credentials request. Only RTs are transferable between ADAL and MSAL
return false;
}
if (ServiceBundle.PlatformProxy.LegacyCacheRequiresSerialization &&
!(this as ITokenCacheInternal).IsAppSubscribedToSerializationEvents())
{
// serialization is not configured but is required
return false;
}
if (!ServiceBundle.Config.LegacyCacheCompatibilityEnabled)
{
// disabled by app developer
return false;
}
if (requestParams.AuthorityInfo.AuthorityType != AuthorityType.Aad)
{
// ADAL did not support B2C
return false;
}
requestParams.RequestContext.Logger.Info("IsLegacyAdalCacheEnabled: yes");
return true;
}
private void SaveToLegacyAdalCache(
AuthenticationRequestParameters requestParams,
MsalTokenResponse response,
MsalRefreshTokenCacheItem msalRefreshTokenCacheItem,
MsalIdTokenCacheItem msalIdTokenCacheItem,
string tenantId,
InstanceDiscoveryMetadataEntry instanceDiscoveryMetadata)
{
if (msalRefreshTokenCacheItem?.RawClientInfo != null &&
msalIdTokenCacheItem?.IdToken?.GetUniqueId() != null &&
IsLegacyAdalCacheEnabled(requestParams))
{
var tenantedAuthority = Authority.CreateAuthorityWithTenant(requestParams.AuthorityInfo, tenantId);
var authorityWithPreferredCache = Authority.CreateAuthorityWithEnvironment(
tenantedAuthority.AuthorityInfo,
instanceDiscoveryMetadata.PreferredCache);
CacheFallbackOperations.WriteAdalRefreshToken(
requestParams.RequestContext.Logger,
LegacyCachePersistence,
msalRefreshTokenCacheItem,
msalIdTokenCacheItem,
authorityWithPreferredCache.AuthorityInfo.CanonicalAuthority.ToString(),
msalIdTokenCacheItem.IdToken.GetUniqueId(),
response.Scope);
}
else
{
requestParams.RequestContext.Logger.Verbose(() => "Not saving to ADAL legacy cache. ");
}
}
/// <summary>
/// Important note: we should not be suggesting expiration dates that are in the past, as it breaks some cache implementations.
/// </summary>
internal /* for testing */ static DateTimeOffset? CalculateSuggestedCacheExpiry(
ITokenCacheAccessor accessor,
ILoggerAdapter logger)
{
// If we have refresh tokens in the cache, we cannot suggest expiration
// because refresh token expiration is not disclosed to SDKs and RTs are long lived anyway (3 months by default)
if (accessor.GetAllRefreshTokens().Count == 0)
{
var tokenCacheItems = accessor.GetAllAccessTokens(optionalPartitionKey: null);
if (tokenCacheItems.Count == 0)
{
logger.Warning("[CalculateSuggestedCacheExpiry] No access tokens or refresh tokens found in the accessor. Not returning any expiration.");
return null;
}
DateTimeOffset cacheExpiry = tokenCacheItems.Max(item => item.ExpiresOn);
// do not suggest an expiration date from the past or within 5 min, as tokens will not be usable anyway
// and HasTokens will be set to false, letting implementers know to delete the cache node
if (cacheExpiry < DateTimeOffset.UtcNow + Constants.AccessTokenExpirationBuffer)
{
return null;
}
return cacheExpiry;
}
return null;
}
private void MergeWamAccountIds(MsalAccountCacheItem msalAccountCacheItem)
{
var existingAccount = Accessor.GetAccount(msalAccountCacheItem);
var existingWamAccountIds = existingAccount?.WamAccountIds;
msalAccountCacheItem.WamAccountIds.MergeDifferentEntries(existingWamAccountIds);
}
#endregion
#region FindAccessToken
/// <summary>
/// IMPORTANT: this class is performance critical; any changes must be benchmarked using Microsoft.Identity.Test.Performance.
/// More information about how to test and what data to look for is in https://aka.ms/msal-net-performance-testing.
///
/// Scenario: client_creds with default in-memory cache can get to ~500k tokens
/// </summary>
async Task<MsalAccessTokenCacheItem> ITokenCacheInternal.FindAccessTokenAsync(
AuthenticationRequestParameters requestParams)
{
var logger = requestParams.RequestContext.Logger;
// no authority passed
if (requestParams.AuthorityInfo?.CanonicalAuthority == null)
{
logger.Warning("[FindAccessTokenAsync] No authority provided. Skipping cache lookup. ");
return null;
}
// take a snapshot of the access tokens to avoid problems where the underlying collection is changed,
// as this method is NOT locked by the semaphore
string partitionKey = CacheKeyFactory.GetKeyFromRequest(requestParams);
Debug.Assert(partitionKey != null || !requestParams.AppConfig.IsConfidentialClient, "On confidential client, cache must be partitioned.");
var accessTokens = Accessor.GetAllAccessTokens(partitionKey, logger);
requestParams.RequestContext.Logger.Always($"[FindAccessTokenAsync] Discovered {accessTokens.Count} access tokens in cache using partition key: {partitionKey}");
if (accessTokens.Count == 0)
{
logger.Verbose(() => "[FindAccessTokenAsync] No access tokens found in the cache. Skipping filtering. ");
requestParams.RequestContext.ApiEvent.CacheInfo = CacheRefreshReason.NoCachedAccessToken;
return null;
}
FilterTokensByHomeAccountTenantOrAssertion(accessTokens, requestParams);
FilterTokensByTokenType(accessTokens, requestParams);
FilterTokensByScopes(accessTokens, requestParams);
accessTokens = await FilterTokensByEnvironmentAsync(accessTokens, requestParams).ConfigureAwait(false);
FilterTokensByClientId(accessTokens);
FilterTokensByAdditionalKeyComponents(accessTokens, requestParams);
CacheRefreshReason cacheInfoTelemetry = CacheRefreshReason.NotApplicable;
// no match
if (accessTokens.Count == 0)
{
logger.Verbose(() => "[FindAccessTokenAsync] No tokens found for matching authority, client_id, user and scopes. ");
return null;
}
MsalAccessTokenCacheItem msalAccessTokenCacheItem = GetSingleToken(accessTokens, requestParams);
msalAccessTokenCacheItem = FilterTokensByPopKeyId(msalAccessTokenCacheItem, requestParams);
msalAccessTokenCacheItem = FilterTokensByExpiry(msalAccessTokenCacheItem, requestParams);
if (msalAccessTokenCacheItem == null)
{
cacheInfoTelemetry = CacheRefreshReason.Expired;
}
requestParams.RequestContext.ApiEvent.CacheInfo = cacheInfoTelemetry;
return msalAccessTokenCacheItem;
}
// Symmetric filter for AdditionalCacheKeyComponents (GH #5963):
// request WITH components -> keep ONLY items with matching components
// request WITHOUT components -> keep ONLY items without components
private void FilterTokensByAdditionalKeyComponents(List<MsalAccessTokenCacheItem> accessTokens, AuthenticationRequestParameters requestParams)
{
bool requestHasComponents =
requestParams.CacheKeyComponents != null &&
requestParams.CacheKeyComponents.Count > 0;
int countBeforeFilter = accessTokens.Count;
if (requestHasComponents)
{
accessTokens.FilterWithLogging(item =>
item.AdditionalCacheKeyComponents != null &&
CollectionHelpers.AreDictionariesEqual(item.AdditionalCacheKeyComponents, requestParams.CacheKeyComponents),
requestParams.RequestContext.Logger,
"Filtering by additional key components");
}
else
{
accessTokens.FilterWithLogging(item =>
item.AdditionalCacheKeyComponents == null ||
item.AdditionalCacheKeyComponents.Count == 0,
requestParams.RequestContext.Logger,
"Filtering out tokens that have additional key components");
}
// Only attribute the miss to this filter if it is actually responsible for
// emptying the candidate set (i.e., entered with > 0 and exited with 0).
if (countBeforeFilter > 0 && accessTokens.Count == 0)
{
requestParams.RequestContext.Logger.Verbose(() => "No tokens found that match the additional key components filter. ");
}
}
private static void FilterTokensByScopes(
List<MsalAccessTokenCacheItem> tokenCacheItems,
AuthenticationRequestParameters requestParams)
{
var logger = requestParams.RequestContext.Logger;
if (tokenCacheItems.Count == 0)
{
logger.Verbose(() => "Not filtering by scopes, because there are no candidates");
return;
}
var requestScopes = requestParams.Scope.Where(s =>
!OAuth2Value.ReservedScopes.Contains(s));
tokenCacheItems.FilterWithLogging(
item =>
{
bool accepted = ScopeHelper.ScopeContains(item.ScopeSet, requestScopes);
if (logger.IsLoggingEnabled(LogLevel.Verbose))
{
logger.Verbose(() => $"Access token with scopes {string.Join(" ", item.ScopeSet)} " + $"passes scope filter? {accepted} ");
}
return accepted;
},
logger,
"Filtering by scopes");
}
private static void FilterTokensByTokenType(
List<MsalAccessTokenCacheItem> tokenCacheItems,
AuthenticationRequestParameters requestParams)
{
tokenCacheItems.FilterWithLogging(item =>
string.Equals(
item.TokenType ?? BearerAuthenticationOperation.BearerTokenType,
requestParams.AuthenticationScheme.AccessTokenType,
StringComparison.OrdinalIgnoreCase),
requestParams.RequestContext.Logger,
"Filtering by token type");
}
private static void FilterTokensByHomeAccountTenantOrAssertion(
List<MsalAccessTokenCacheItem> tokenCacheItems,
AuthenticationRequestParameters requestParams)
{
string requestTenantId = requestParams.Authority.TenantId;
bool filterByTenantId = true;
if (ApiEvent.IsOnBehalfOfRequest(requestParams.ApiId))
{
tokenCacheItems.FilterWithLogging(item =>
!string.IsNullOrEmpty(item.OboCacheKey) &&
item.OboCacheKey.Equals(
!string.IsNullOrEmpty(requestParams.LongRunningOboCacheKey) ? requestParams.LongRunningOboCacheKey : requestParams.UserAssertion.AssertionHash,
StringComparison.OrdinalIgnoreCase),
requestParams.RequestContext.Logger,
!string.IsNullOrEmpty(requestParams.LongRunningOboCacheKey) ?
$"Filtering AT by user-provided cache key: {requestParams.LongRunningOboCacheKey}" :
$"Filtering AT by user assertion: {requestParams.UserAssertion.AssertionHash}");
// OBO calls FindAccessTokenAsync directly, but we are not able to resolve the authority
// unless the developer has configured a tenanted authority. If they have configured /common
// then we cannot filter by tenant and will use whatever is in the cache.
filterByTenantId =
!string.IsNullOrEmpty(requestTenantId) &&
!AadAuthority.IsCommonOrOrganizationsTenant(requestTenantId);
}
if (filterByTenantId)
{
tokenCacheItems.FilterWithLogging(item =>
string.Equals(item.TenantId ?? string.Empty, requestTenantId ?? string.Empty, StringComparison.OrdinalIgnoreCase),
requestParams.RequestContext.Logger,
"Filtering AT by tenant id");
}
else
{
requestParams.RequestContext.Logger.Warning("Have not filtered by tenant ID. " +
"This can happen in OBO scenario where authority is /common or /organizations. " +
"Please use tenanted authority.");
}
// Only AcquireTokenSilent has an IAccount in the request that can be used for filtering
if (requestParams.ApiId != ApiEvent.ApiIds.AcquireTokenForClient &&
requestParams.ApiId != ApiEvent.ApiIds.AcquireTokenForSystemAssignedManagedIdentity &&
requestParams.ApiId != ApiEvent.ApiIds.AcquireTokenForUserAssignedManagedIdentity &&
!ApiEvent.IsOnBehalfOfRequest(requestParams.ApiId))
{
tokenCacheItems.FilterWithLogging(item => item.HomeAccountId.Equals(
requestParams.Account.HomeAccountId?.Identifier, StringComparison.OrdinalIgnoreCase),
requestParams.RequestContext.Logger,
"Filtering AT by home account id");
}
}
private MsalAccessTokenCacheItem FilterTokensByExpiry(
MsalAccessTokenCacheItem msalAccessTokenCacheItem,
AuthenticationRequestParameters requestParams)
{
var logger = requestParams.RequestContext.Logger;
if (msalAccessTokenCacheItem != null)
{
if (msalAccessTokenCacheItem.ExpiresOn > DateTime.UtcNow + Constants.AccessTokenExpirationBuffer)
{
// due to https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/1806
if (msalAccessTokenCacheItem.ExpiresOn > DateTime.UtcNow + TimeSpan.FromDays(ExpirationTooLongInDays))
{
logger.Error(
"Access token expiration too large. This can be the result of a bug or corrupt cache. Token will be ignored as it is likely expired." +
GetAccessTokenExpireLogMessageContent(msalAccessTokenCacheItem));
return null;
}
logger.Info(
() => "Access token is not expired. Returning the found cache entry. " +
GetAccessTokenExpireLogMessageContent(msalAccessTokenCacheItem));
return msalAccessTokenCacheItem;
}
if (ServiceBundle.Config.IsExtendedTokenLifetimeEnabled &&
msalAccessTokenCacheItem.ExtendedExpiresOn > DateTime.UtcNow + Constants.AccessTokenExpirationBuffer)
{
logger.Info(() =>
"Access token is expired. IsExtendedLifeTimeEnabled=TRUE and ExtendedExpiresOn is not exceeded. Returning the found cache entry. " +
GetAccessTokenExpireLogMessageContent(msalAccessTokenCacheItem));
msalAccessTokenCacheItem.IsExtendedLifeTimeToken = true;
return msalAccessTokenCacheItem;
}
logger.Info(() =>
"Access token has expired or about to expire. " +
GetAccessTokenExpireLogMessageContent(msalAccessTokenCacheItem));
}
return null;
}
private static MsalAccessTokenCacheItem GetSingleToken(
List<MsalAccessTokenCacheItem> tokenCacheItems,
AuthenticationRequestParameters requestParams)
{
// if only one cached token found
if (tokenCacheItems.Count == 1)
{
return tokenCacheItems[0];
}
requestParams.RequestContext.Logger.Error("Multiple access tokens found for matching authority, client_id, user and scopes. ");
throw new MsalClientException(
MsalError.MultipleTokensMatchedError,
MsalErrorMessage.MultipleTokensMatched);
}
private async Task<List<MsalAccessTokenCacheItem>> FilterTokensByEnvironmentAsync(
List<MsalAccessTokenCacheItem> tokenCacheItems,
AuthenticationRequestParameters requestParams)
{
var logger = requestParams.RequestContext.Logger;
if (tokenCacheItems.Count == 0)
{
logger.Verbose(() => "Not filtering AT by environment, because there are no candidates");
return tokenCacheItems;
}
// at this point we need environment aliases, try to get them without a discovery call
var instanceMetadata = await ServiceBundle.InstanceDiscoveryManager.GetMetadataEntryTryAvoidNetworkAsync(
requestParams.AuthorityInfo,
tokenCacheItems.Select(at => at.Environment), // if all environments are known, a network call can be avoided
requestParams.RequestContext)
.ConfigureAwait(false);
// In case we're sharing the cache with an MSAL that does not implement environment aliasing,
// it's possible (but unlikely), that we have multiple ATs from the same alias family.
// To overcome some of these use cases, try to filter just by preferred cache alias
var itemsFilteredByAlias = tokenCacheItems.FilterWithLogging(
item => item.Environment.Equals(instanceMetadata.PreferredCache, StringComparison.OrdinalIgnoreCase),
requestParams.RequestContext.Logger,
$"Filtering AT by preferred environment {instanceMetadata.PreferredCache}",
updateOriginalCollection: false);
if (itemsFilteredByAlias.Count > 0)
{
if (logger.IsLoggingEnabled(LogLevel.Verbose))
{
logger.Verbose(() => $"Filtered AT by preferred alias returning {itemsFilteredByAlias.Count} tokens.");
}
return itemsFilteredByAlias;
}
return tokenCacheItems.FilterWithLogging(
item => instanceMetadata.Aliases.ContainsOrdinalIgnoreCase(item.Environment),
requestParams.RequestContext.Logger,
$"Filtering AT by environment");
}
private static MsalAccessTokenCacheItem FilterTokensByPopKeyId(MsalAccessTokenCacheItem item, AuthenticationRequestParameters authenticationRequest)
{
if (item == null)
{
return null;
}
string requestKid = authenticationRequest.AuthenticationScheme.KeyId;
if (string.IsNullOrEmpty(item.KeyId) && string.IsNullOrEmpty(requestKid))
{
authenticationRequest.RequestContext.Logger.Verbose(() => "Bearer token found");
return item;
}
if (string.Equals(item.KeyId, requestKid, StringComparison.OrdinalIgnoreCase))
{
authenticationRequest.RequestContext.Logger.Verbose(() => "Keyed token found");
return item;
}
authenticationRequest.RequestContext.Logger.Info(
() => $"A token bound to the wrong key was found. Token key id: {item.KeyId} Request key id: {requestKid}");
return null;
}
#endregion
private void FilterTokensByClientId<T>(List<T> tokenCacheItems) where T : MsalCredentialCacheItemBase
{
tokenCacheItems.RemoveAll(x => !x.ClientId.Equals(ClientId, StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// For testing purposes only. Expires ALL access tokens in memory and fires OnAfterAccessAsync event with no cache key
/// </summary>
internal async Task ExpireAllAccessTokensForTestAsync()
{
ITokenCacheInternal tokenCacheInternal = this;
var accessor = tokenCacheInternal.Accessor;
var allAccessTokens = accessor.GetAllAccessTokens();
foreach (MsalAccessTokenCacheItem atItem in allAccessTokens)
{
accessor.SaveAccessToken(atItem.WithExpiresOn(DateTimeOffset.UtcNow));
}
if (tokenCacheInternal.IsAppSubscribedToSerializationEvents())
{
var args = new TokenCacheNotificationArgs(
tokenCache: this,
clientId: ClientId,
account: null,
hasStateChanged: true,
tokenCacheInternal.IsApplicationCache,
suggestedCacheKey: null,
hasTokens: tokenCacheInternal.HasTokensNoLocks(),
suggestedCacheExpiry: null,
cancellationToken: default,
correlationId: default,
requestScopes: null,
requestTenantId: null,
identityLogger: null,
piiLoggingEnabled: false);
await tokenCacheInternal.OnAfterAccessAsync(args).ConfigureAwait(false);
}
}
async Task<MsalRefreshTokenCacheItem> ITokenCacheInternal.FindRefreshTokenAsync(
AuthenticationRequestParameters requestParams,
string familyId)
{
if (requestParams.Authority == null)
{
return null;
}
var requestKey = CacheKeyFactory.GetKeyFromRequest(requestParams);
var refreshTokens = Accessor.GetAllRefreshTokens(requestKey);
requestParams.RequestContext.Logger.Always($"[FindRefreshTokenAsync] Discovered {refreshTokens.Count} refresh tokens in cache using key: {requestKey}");
if (refreshTokens.Count != 0)
{
FilterRefreshTokensByHomeAccountIdOrAssertion(refreshTokens, requestParams, familyId);
if (!requestParams.AppConfig.MultiCloudSupportEnabled)
{
var metadata =
await ServiceBundle.InstanceDiscoveryManager.GetMetadataEntryTryAvoidNetworkAsync(
requestParams.AuthorityInfo,
refreshTokens.Select(rt => rt.Environment), // if all environments are known, a network call can be avoided
requestParams.RequestContext)
.ConfigureAwait(false);
var aliases = metadata.Aliases;
refreshTokens.RemoveAll(
item => !aliases.ContainsOrdinalIgnoreCase(item.Environment));
}
requestParams.RequestContext.Logger.Info(() => "[FindRefreshTokenAsync] Refresh token found in the cache? - " + (refreshTokens.Count != 0));
if (refreshTokens.Count > 0)
{
return refreshTokens.FirstOrDefault();
}
}
else
{
requestParams.RequestContext.Logger.Verbose(() => "[FindRefreshTokenAsync] No RTs found in the MSAL cache ");
}
requestParams.RequestContext.Logger.Verbose(() => "[FindRefreshTokenAsync] Checking ADAL cache for matching RT. ");
if (IsLegacyAdalCacheEnabled(requestParams) &&
requestParams.Account != null &&
string.IsNullOrEmpty(familyId)) // ADAL legacy cache does not store FRTs
{
var metadata =
await ServiceBundle.InstanceDiscoveryManager.GetMetadataEntryTryAvoidNetworkAsync(
requestParams.AuthorityInfo,
refreshTokens.Select(rt => rt.Environment), // if all environments are known, a network call can be avoided
requestParams.RequestContext)
.ConfigureAwait(false);
var aliases = metadata.Aliases;
return CacheFallbackOperations.GetRefreshToken(
requestParams.RequestContext.Logger,
LegacyCachePersistence,
aliases,
requestParams.AppConfig.ClientId,
requestParams.Account);
}
return null;
}
private static void FilterRefreshTokensByHomeAccountIdOrAssertion(
List<MsalRefreshTokenCacheItem> cacheItems,
AuthenticationRequestParameters requestParams,
string familyId)
{
if (ApiEvent.IsOnBehalfOfRequest(requestParams.ApiId))
{
cacheItems.FilterWithLogging(item =>
!string.IsNullOrEmpty(item.OboCacheKey) &&
item.OboCacheKey.Equals(
!string.IsNullOrEmpty(requestParams.LongRunningOboCacheKey) ? requestParams.LongRunningOboCacheKey : requestParams.UserAssertion.AssertionHash,
StringComparison.OrdinalIgnoreCase),
requestParams.RequestContext.Logger,
!string.IsNullOrEmpty(requestParams.LongRunningOboCacheKey) ?
$"Filtering RT by user-provided cache key: {requestParams.LongRunningOboCacheKey}" :
$"Filtering RT by user assertion: {requestParams.UserAssertion.AssertionHash}");
}
else
{
cacheItems.FilterWithLogging(item => item.HomeAccountId.Equals(
requestParams.Account.HomeAccountId?.Identifier, StringComparison.OrdinalIgnoreCase),
requestParams.RequestContext.Logger,
"Filtering RT by home account id");
}
// This will also filter for the case when familyId is null and exclude RTs with familyId in filtered list
cacheItems.FilterWithLogging(item =>
string.Equals(item.FamilyId ?? string.Empty,
familyId ?? string.Empty, StringComparison.OrdinalIgnoreCase),
requestParams.RequestContext.Logger,
"Filtering RT by family id");
// if there is a value in familyId, we are looking for FRT and hence ignore filter with clientId
if (string.IsNullOrEmpty(familyId))
{
cacheItems.FilterWithLogging(item => item.ClientId.Equals(
requestParams.AppConfig.ClientId, StringComparison.OrdinalIgnoreCase),
requestParams.RequestContext.Logger,
"Filtering RT by client id");
}
}
async Task<bool?> ITokenCacheInternal.IsFociMemberAsync(AuthenticationRequestParameters requestParams, string familyId)
{
var logger = requestParams.RequestContext.Logger;
if (requestParams?.AuthorityInfo?.CanonicalAuthority == null)
{
logger.Warning("No authority details, can't check app metadata. Returning unknown. ");
return null;
}
var allAppMetadata = Accessor.GetAllAppMetadata();
var instanceMetadata = await ServiceBundle.InstanceDiscoveryManager.GetMetadataEntryTryAvoidNetworkAsync(
requestParams.AuthorityInfo,
allAppMetadata.Select(m => m.Environment),
requestParams.RequestContext)
.ConfigureAwait(false);
var appMetadata =
instanceMetadata.Aliases
.Select(env => Accessor.GetAppMetadata(new MsalAppMetadataCacheItem(ClientId, env, null)))
.FirstOrDefault(item => item != null);
// From a FOCI perspective, an app has 3 states - in the family, not in the family or unknown
// Unknown is a valid state, where we never fetched tokens for that app or when we used an older
// version of MSAL which did not record app metadata.
if (appMetadata == null)
{
logger.Verbose(() => "No app metadata found. Returning unknown. ");
return null;
}
return appMetadata.FamilyId == familyId;
}
/// <remarks>
/// Get accounts should not make a network call, if possible. This can be achieved if
/// all the environments in the token cache are known to MSAL, as MSAL keeps a list of
/// known environments in <see cref="KnownMetadataProvider"/>
/// </remarks>
async Task<IEnumerable<IAccount>> ITokenCacheInternal.GetAccountsAsync(AuthenticationRequestParameters requestParameters)
{
var logger = requestParameters.RequestContext.Logger;
var environment = requestParameters.AuthorityInfo.Host;
// FOCI is only enabled on public client desktop apps
bool filterByClientId = !(requestParameters.AppConfig.IsPublicClient && _featureFlags.IsFociEnabled);
// this will either be the home account ID or null, it can never be OBO assertion or tenant ID
string partitionKey = CacheKeyFactory.GetKeyFromRequest(requestParameters);
logger.VerbosePii(() => $"[GetAccounts] PartitionKey: {partitionKey}. request.HomeAccountId {requestParameters.HomeAccountId}", () => "");
var refreshTokenCacheItems = Accessor.GetAllRefreshTokens(partitionKey);
var accountCacheItems = Accessor.GetAllAccounts(partitionKey);
if (filterByClientId)
{
refreshTokenCacheItems.FilterWithLogging(item =>
string.Equals(item.ClientId, ClientId, StringComparison.OrdinalIgnoreCase),
logger,
"[GetAccounts] Filtering RTs by clientID",
true);
}
logger.Verbose(() => $"[GetAccounts] Found {refreshTokenCacheItems.Count} RTs and {accountCacheItems.Count} accounts in MSAL cache before env filtering.");
// Multi-cloud support - must filter by environment.
ISet<string> allEnvironmentsInCache = new HashSet<string>(