| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | using Microsoft.Identity.Client; |
| | 5 | | using System; |
| | 6 | | using System.IO; |
| | 7 | | using System.Threading.Tasks; |
| | 8 | | using System.Security.Cryptography; |
| | 9 | |
|
| | 10 | | namespace Azure.Identity |
| | 11 | | { |
| | 12 | | internal class MsalCacheReader |
| | 13 | | { |
| | 14 | | private readonly string _cachePath; |
| | 15 | | private readonly string _cacheLockPath; |
| | 16 | | private readonly int _cacheRetryCount; |
| | 17 | | private readonly TimeSpan _cacheRetryDelay; |
| | 18 | | private DateTimeOffset _lastReadTime; |
| | 19 | |
|
| 0 | 20 | | public MsalCacheReader(ITokenCache cache, string cachePath, int cacheRetryCount, TimeSpan cacheRetryDelay) |
| | 21 | | { |
| 0 | 22 | | _cachePath = cachePath; |
| | 23 | |
|
| 0 | 24 | | _cacheLockPath = cachePath + ".lockfile"; |
| | 25 | |
|
| 0 | 26 | | _cacheRetryCount = cacheRetryCount; |
| | 27 | |
|
| 0 | 28 | | _cacheRetryDelay = cacheRetryDelay; |
| | 29 | |
|
| 0 | 30 | | cache.SetBeforeAccessAsync(OnBeforeAccessAsync); |
| 0 | 31 | | } |
| | 32 | |
|
| | 33 | | private async Task OnBeforeAccessAsync(TokenCacheNotificationArgs args) |
| | 34 | | { |
| | 35 | | try |
| | 36 | | { |
| 0 | 37 | | DateTime cacheTimestamp = File.GetLastWriteTimeUtc(_cachePath); |
| | 38 | |
|
| 0 | 39 | | if (File.Exists(_cachePath) && _lastReadTime < cacheTimestamp) |
| | 40 | | { |
| 0 | 41 | | using (SentinelFileLock cacheLock = await SentinelFileLock.AcquireAsync(_cacheLockPath, _cacheRetryC |
| | 42 | | { |
| 0 | 43 | | byte[] cacheBytesFromDisk = await ReadCacheFromProtectedStorageAsync().ConfigureAwait(false); |
| | 44 | |
|
| | 45 | | // update the last read time before deserialization so if deserialization fails we won't continu |
| 0 | 46 | | _lastReadTime = cacheTimestamp; |
| | 47 | |
|
| 0 | 48 | | if (cacheBytesFromDisk != null) |
| | 49 | | { |
| 0 | 50 | | args.TokenCache.DeserializeMsalV3(cacheBytesFromDisk, shouldClearExistingCache: false); |
| | 51 | | } |
| 0 | 52 | | } |
| | 53 | | } |
| 0 | 54 | | } |
| 0 | 55 | | catch (Exception) |
| | 56 | | { |
| | 57 | | // log |
| 0 | 58 | | } |
| 0 | 59 | | } |
| | 60 | |
|
| | 61 | | private async Task<byte[]> ReadCacheFromProtectedStorageAsync() |
| | 62 | | { |
| 0 | 63 | | using (FileStream file = File.OpenRead(_cachePath)) |
| | 64 | | { |
| 0 | 65 | | byte[] protectedBytes = new byte[file.Length]; |
| | 66 | |
|
| 0 | 67 | | await file.ReadAsync(protectedBytes, 0, protectedBytes.Length).ConfigureAwait(false); |
| | 68 | |
|
| 0 | 69 | | return ProtectedData.Unprotect(protectedBytes, optionalEntropy: null, scope: DataProtectionScope.Current |
| | 70 | | } |
| 0 | 71 | | } |
| | 72 | | } |
| | 73 | |
|
| | 74 | | } |