Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -97,5 +97,10 @@ public AuthenticationResultMetadata(TokenSource tokenSource)
/// See https://aka.ms/msal-net-logging for more details about logging.
/// </remarks>
public string Telemetry { get; set; }

/// <summary>
/// The number of access tokens in the cache.
/// </summary>
public int CachedAccessTokenCount { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,11 @@ public async Task<MsalAccessTokenCacheItem> FindAccessTokenAsync()
return await TokenCacheInternal.FindAccessTokenAsync(_requestParams).ConfigureAwait(false);
}

public Task<Tuple<MsalAccessTokenCacheItem, MsalIdTokenCacheItem, Account>> SaveTokenResponseAsync(MsalTokenResponse tokenResponse)
public async Task<Tuple<MsalAccessTokenCacheItem, MsalIdTokenCacheItem, Account>> SaveTokenResponseAsync(MsalTokenResponse tokenResponse)
{
return TokenCacheInternal.SaveTokenResponseAsync(_requestParams, tokenResponse);
var result = await TokenCacheInternal.SaveTokenResponseAsync(_requestParams, tokenResponse).ConfigureAwait(false);
RequestContext.ApiEvent.CachedAccessTokenCount = TokenCacheInternal.Accessor.EntryCount;
return result;
}

public async Task<Account> GetAccountAssociatedWithAccessTokenAsync(MsalAccessTokenCacheItem msalAccessTokenCacheItem)
Expand Down Expand Up @@ -181,6 +183,8 @@ private async Task RefreshCacheForReadOperationsAsync()
{
RequestContext.ApiEvent.CacheLevel = CacheLevel.L1Cache;
}

RequestContext.ApiEvent.CachedAccessTokenCount = TokenCacheInternal.Accessor.EntryCount;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ namespace Microsoft.Identity.Client.Cache
{
internal interface ITokenCacheAccessor
{
int EntryCount { get; }

void SaveAccessToken(MsalAccessTokenCacheItem item);

void SaveRefreshToken(MsalRefreshTokenCacheItem item);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ private void UpdateTelemetry(long elapsedMilliseconds, ApiEvent apiEvent, Authen
authenticationResult.AuthenticationResultMetadata.CacheLevel = GetCacheLevel(authenticationResult);
authenticationResult.AuthenticationResultMetadata.Telemetry = apiEvent.MsalRuntimeTelemetry;
authenticationResult.AuthenticationResultMetadata.RegionDetails = CreateRegionDetails(apiEvent);
authenticationResult.AuthenticationResultMetadata.CachedAccessTokenCount = apiEvent.CachedAccessTokenCount;

Metrics.IncrementTotalDurationInMs(authenticationResult.AuthenticationResultMetadata.DurationTotalInMs);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,8 @@ public List<MsalAccountCacheItem> GetAllAccounts(string optionalPartitionKey = n
}
#endregion

public int EntryCount { get; } = 0; // not implemented for Android

public MsalAccountCacheItem GetAccount(MsalAccountCacheItem accountCacheItem)
{
return MsalAccountCacheItem.FromJsonString(_accountSharedPreference.GetString(accountCacheItem.CacheKey, null));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,10 @@ public List<MsalAccountCacheItem> GetAllAccounts(string optionalPartitionKey = n
.Select(x => MsalAccountCacheItem.FromJsonString(x))
.ToList();
}
#endregion
#endregion

public int EntryCount { get; } = 0; // not implemented for iOS


internal SecStatusCode TryGetBrokerApplicationToken(string clientId, out string appToken)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.Identity.Client.Cache;
using Microsoft.Identity.Client.Cache.Items;
using Microsoft.Identity.Client.Core;
Expand Down Expand Up @@ -34,6 +35,11 @@ internal class InMemoryPartitionedAppTokenCacheAccessor : ITokenCacheAccessor
protected readonly ILoggerAdapter _logger;
private readonly CacheOptions _tokenCacheAccessorOptions;

private int _entryCount = 0;
private static int s_entryCount = 0;

public int EntryCount => GetEntryCountRef();

public InMemoryPartitionedAppTokenCacheAccessor(
ILoggerAdapter logger,
CacheOptions tokenCacheAccessorOptions)
Expand All @@ -59,9 +65,18 @@ public void SaveAccessToken(MsalAccessTokenCacheItem item)
string itemKey = item.CacheKey;
string partitionKey = CacheKeyFactory.GetAppTokenCacheItemKey(item.ClientId, item.TenantId, item.KeyId, item.AdditionalCacheKeyComponents);

// if a conflict occurs, pick the latest value
AccessTokenCacheDictionary
.GetOrAdd(partitionKey, new ConcurrentDictionary<string, MsalAccessTokenCacheItem>())[itemKey] = item;
var partition = AccessTokenCacheDictionary.GetOrAdd(partitionKey, _ => new ConcurrentDictionary<string, MsalAccessTokenCacheItem>());
bool added = partition.TryAdd(itemKey, item);

// only increment the entry count if the item was added, not updated
if (added)
{
Interlocked.Increment(ref GetEntryCountRef());
}
else
{
partition[itemKey] = item;
}
}

/// <summary>
Expand Down Expand Up @@ -129,12 +144,19 @@ public void DeleteAccessToken(MsalAccessTokenCacheItem item)
{
var partitionKey = CacheKeyFactory.GetAppTokenCacheItemKey(item.ClientId, item.TenantId, item.KeyId);

AccessTokenCacheDictionary.TryGetValue(partitionKey, out var partition);
if (partition == null || !partition.TryRemove(item.CacheKey, out _))
if (AccessTokenCacheDictionary.TryGetValue(partitionKey, out var partition))
{
_logger.InfoPii(
() => $"[Internal cache] Cannot delete access token because it was not found in the cache. Key {item.CacheKey}.",
() => "[Internal cache] Cannot delete access token because it was not found in the cache.");
bool removed = partition.TryRemove(item.CacheKey, out _);
if (removed)
{
Interlocked.Decrement(ref GetEntryCountRef());
}
else
{
_logger.InfoPii(
() => $"[Internal cache] Cannot delete access token because it was not found in the cache. Key {item.CacheKey}.",
() => "[Internal cache] Cannot delete access token because it was not found in the cache.");
}
}
}

Expand Down Expand Up @@ -219,6 +241,7 @@ public virtual void Clear(ILoggerAdapter requestlogger = null)
{
var logger = requestlogger ?? _logger;
AccessTokenCacheDictionary.Clear();
Interlocked.Exchange(ref GetEntryCountRef(), 0);
logger.Always("[Internal cache] Clearing app token cache accessor.");
// app metadata isn't removable
}
Expand All @@ -227,5 +250,11 @@ public virtual bool HasAccessOrRefreshTokens()
{
return AccessTokenCacheDictionary.Any(partition => partition.Value.Any(token => !token.Value.IsExpiredWithBuffer()));
}

private ref int GetEntryCountRef()
{
return ref _tokenCacheAccessorOptions.UseSharedCache ? ref s_entryCount : ref _entryCount;
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,15 @@ internal class InMemoryPartitionedUserTokenCacheAccessor : ITokenCacheAccessor
private static readonly ConcurrentDictionary<string, MsalAppMetadataCacheItem> s_appMetadataDictionary =
new ConcurrentDictionary<string, MsalAppMetadataCacheItem>();

private static int s_entryCount = 0;

protected readonly ILoggerAdapter _logger;
private readonly CacheOptions _tokenCacheAccessorOptions;

private int _entryCount = 0;

public int EntryCount => GetEntryCountRef();

public InMemoryPartitionedUserTokenCacheAccessor(ILoggerAdapter logger, CacheOptions tokenCacheAccessorOptions)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
Expand Down Expand Up @@ -73,8 +79,17 @@ public void SaveAccessToken(MsalAccessTokenCacheItem item)
string itemKey = item.CacheKey;
string partitionKey = CacheKeyFactory.GetKeyFromCachedItem(item);

AccessTokenCacheDictionary
.GetOrAdd(partitionKey, new ConcurrentDictionary<string, MsalAccessTokenCacheItem>())[itemKey] = item; // if a conflict occurs, pick the latest value
var partition = AccessTokenCacheDictionary.GetOrAdd(partitionKey, _ => new ConcurrentDictionary<string, MsalAccessTokenCacheItem>());
bool added = partition.TryAdd(itemKey, item);
// only increment the entry count if this is a new item
if (added)
{
System.Threading.Interlocked.Increment(ref GetEntryCountRef());
}
else
{
partition[itemKey] = item;
}
}

public void SaveRefreshToken(MsalRefreshTokenCacheItem item)
Expand Down Expand Up @@ -151,12 +166,19 @@ public void DeleteAccessToken(MsalAccessTokenCacheItem item)
{
string partitionKey = CacheKeyFactory.GetKeyFromCachedItem(item);

AccessTokenCacheDictionary.TryGetValue(partitionKey, out var partition);
if (partition == null || !partition.TryRemove(item.CacheKey, out _))
if (AccessTokenCacheDictionary.TryGetValue(partitionKey, out var partition))
{
_logger.InfoPii(
() => $"[Internal cache] Cannot delete access token because it was not found in the cache. Key {item.CacheKey}.",
() => "[Internal cache] Cannot delete access token because it was not found in the cache.");
bool removed = partition.TryRemove(item.CacheKey, out _);
if (removed)
{
System.Threading.Interlocked.Decrement(ref GetEntryCountRef());
}
else
{
_logger.InfoPii(
() => $"[Internal cache] Cannot delete access token because it was not found in the cache. Key {item.CacheKey}.",
() => "[Internal cache] Cannot delete access token because it was not found in the cache.");
}
}
}

Expand Down Expand Up @@ -246,7 +268,7 @@ public virtual List<MsalRefreshTokenCacheItem> GetAllRefreshTokens(string partit
if (RefreshTokenCacheDictionary.Count == 1 && result.Count == 0)
{
logger.VerbosePii(
() => $"[Internal cache] 0 RTs and 1 partition. Partition in cache is {RefreshTokenCacheDictionary.Keys.First()}",
() => $"[Internal cache] 0 RTs and 1 partition. Partition in cache is {RefreshTokenCacheDictionary.Keys.First()}",
() => "[Internal cache] 0 RTs and 1 partition] 0 RTs and 1 partition.");
}
}
Expand Down Expand Up @@ -290,7 +312,7 @@ public virtual List<MsalAccountCacheItem> GetAllAccounts(string partitionKey = n
{
AccountCacheDictionary.TryGetValue(partitionKey, out ConcurrentDictionary<string, MsalAccountCacheItem> partition);
result = partition?.Select(kv => kv.Value)?.ToList() ?? CollectionHelpers.GetEmptyList<MsalAccountCacheItem>();

if (logger.IsLoggingEnabled(LogLevel.Verbose))
{
logger.Verbose(() => $"[Internal cache] GetAllAccounts (with partition - exists? {partition != null}) found {result.Count} accounts.");
Expand Down Expand Up @@ -327,6 +349,8 @@ public virtual void Clear(ILoggerAdapter requestlogger = null)
IdTokenCacheDictionary.Clear();
AccountCacheDictionary.Clear();
// app metadata isn't removable
System.Threading.Interlocked.Exchange(ref GetEntryCountRef(), 0);

}

/// WARNING: this API is slow as it loads all tokens, not just from 1 partition.
Expand All @@ -336,5 +360,10 @@ public virtual bool HasAccessOrRefreshTokens()
return RefreshTokenCacheDictionary.Any(partition => partition.Value.Count > 0) ||
AccessTokenCacheDictionary.Any(partition => partition.Value.Any(token => !token.Value.IsExpiredWithBuffer()));
}

private ref int GetEntryCountRef()
{
return ref _tokenCacheAccessorOptions.UseSharedCache ? ref s_entryCount : ref _entryCount;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ Microsoft.Identity.Client.Utils.MacMainThreadScheduler.IsRunning() -> bool
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.Stop() -> void
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.RunOnMainThreadAsync(System.Func<System.Threading.Tasks.Task> asyncAction) -> System.Threading.Tasks.Task
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.StartMessageLoop() -> void
Microsoft.Identity.Client.AuthenticationResultMetadata.CachedAccessTokenCount.get -> int
Microsoft.Identity.Client.AuthenticationResultMetadata.CachedAccessTokenCount.set -> void
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ Microsoft.Identity.Client.Utils.MacMainThreadScheduler.IsRunning() -> bool
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.Stop() -> void
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.RunOnMainThreadAsync(System.Func<System.Threading.Tasks.Task> asyncAction) -> System.Threading.Tasks.Task
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.StartMessageLoop() -> void
Microsoft.Identity.Client.AuthenticationResultMetadata.CachedAccessTokenCount.get -> int
Microsoft.Identity.Client.AuthenticationResultMetadata.CachedAccessTokenCount.set -> void
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ Microsoft.Identity.Client.Utils.MacMainThreadScheduler.IsRunning() -> bool
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.Stop() -> void
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.RunOnMainThreadAsync(System.Func<System.Threading.Tasks.Task> asyncAction) -> System.Threading.Tasks.Task
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.StartMessageLoop() -> void
Microsoft.Identity.Client.AuthenticationResultMetadata.CachedAccessTokenCount.get -> int
Microsoft.Identity.Client.AuthenticationResultMetadata.CachedAccessTokenCount.set -> void
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ Microsoft.Identity.Client.Utils.MacMainThreadScheduler.IsRunning() -> bool
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.Stop() -> void
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.RunOnMainThreadAsync(System.Func<System.Threading.Tasks.Task> asyncAction) -> System.Threading.Tasks.Task
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.StartMessageLoop() -> void
Microsoft.Identity.Client.AuthenticationResultMetadata.CachedAccessTokenCount.get -> int
Microsoft.Identity.Client.AuthenticationResultMetadata.CachedAccessTokenCount.set -> void
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ Microsoft.Identity.Client.Utils.MacMainThreadScheduler.IsRunning() -> bool
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.Stop() -> void
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.RunOnMainThreadAsync(System.Func<System.Threading.Tasks.Task> asyncAction) -> System.Threading.Tasks.Task
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.StartMessageLoop() -> void
Microsoft.Identity.Client.AuthenticationResultMetadata.CachedAccessTokenCount.get -> int
Microsoft.Identity.Client.AuthenticationResultMetadata.CachedAccessTokenCount.set -> void
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ Microsoft.Identity.Client.Utils.MacMainThreadScheduler.IsRunning() -> bool
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.Stop() -> void
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.RunOnMainThreadAsync(System.Func<System.Threading.Tasks.Task> asyncAction) -> System.Threading.Tasks.Task
Microsoft.Identity.Client.Utils.MacMainThreadScheduler.StartMessageLoop() -> void
Microsoft.Identity.Client.AuthenticationResultMetadata.CachedAccessTokenCount.get -> int
Microsoft.Identity.Client.AuthenticationResultMetadata.CachedAccessTokenCount.set -> void
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ public string ApiIdString

public string ApiErrorCode { get; set; }

public int CachedAccessTokenCount { get; set; }

#region Region
public string RegionUsed { get; set; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ public class AcquireTokenForClientCacheTests

[ParamsAllValues]
public bool EnableCacheSerialization { get; set; }

//[Params(false)]
public bool UseMicrosoftIdentityWebCache { get; set; }

Expand Down
Loading