diff --git a/src/Common/Commands.Common.Test/Common/ProfileCmdltsTests.cs b/src/Common/Commands.Common.Test/Common/ProfileCmdltsTests.cs index c6902a22fdd3..25ad50d3662c 100644 --- a/src/Common/Commands.Common.Test/Common/ProfileCmdltsTests.cs +++ b/src/Common/Commands.Common.Test/Common/ProfileCmdltsTests.cs @@ -149,6 +149,20 @@ public void ClearAzureProfileClearsTokenCache() Assert.Equal(0, tokenCache.ReadItems().Count()); } + [Fact] + public void DeleteCorruptedTokenCache() + { + //setup + string testFileName = @"c:\foobar\TokenCache.dat"; + ProfileClient.DataStore.WriteFile(testFileName, new byte[] { 0, 1 }); + + //Act + ProtectedFileTokenCache tokenCache = new ProtectedFileTokenCache(testFileName); + + //Assert + Assert.False(ProfileClient.DataStore.FileExists(testFileName)); + } + [Fact] public void SetAzureSubscriptionAddsSubscriptionWithCertificate() { diff --git a/src/Common/Commands.Common/Authentication/ProtectedFileTokenCache.cs b/src/Common/Commands.Common/Authentication/ProtectedFileTokenCache.cs index f6e184dc1b0c..f313eed7b143 100644 --- a/src/Common/Commands.Common/Authentication/ProtectedFileTokenCache.cs +++ b/src/Common/Commands.Common/Authentication/ProtectedFileTokenCache.cs @@ -44,22 +44,39 @@ public static ProtectedFileTokenCache Instance // Initializes the cache against a local file. // If the file is already present, it loads its content in the ADAL cache private ProtectedFileTokenCache() + { + Initialize(CacheFileName); + } + + private void Initialize(string fileName) { AfterAccess = AfterAccessNotification; BeforeAccess = BeforeAccessNotification; lock (fileLock) { - if (ProfileClient.DataStore.FileExists(CacheFileName)) + if (ProfileClient.DataStore.FileExists(fileName)) { - var existingData = ProfileClient.DataStore.ReadFileAsBytes(CacheFileName); + var existingData = ProfileClient.DataStore.ReadFileAsBytes(fileName); if (existingData != null) { - Deserialize(ProtectedData.Unprotect(existingData, null, DataProtectionScope.CurrentUser)); + try + { + Deserialize(ProtectedData.Unprotect(existingData, null, DataProtectionScope.CurrentUser)); + } + catch (CryptographicException) + { + ProfileClient.DataStore.DeleteFile(fileName); + } } } } } + public ProtectedFileTokenCache(string cacheFile) + { + Initialize(cacheFile); + } + // Empties the persistent store. public override void Clear() { @@ -81,7 +98,14 @@ void BeforeAccessNotification(TokenCacheNotificationArgs args) var existingData = ProfileClient.DataStore.ReadFileAsBytes(CacheFileName); if (existingData != null) { - Deserialize(ProtectedData.Unprotect(existingData, null, DataProtectionScope.CurrentUser)); + try + { + Deserialize(ProtectedData.Unprotect(existingData, null, DataProtectionScope.CurrentUser)); + } + catch (CryptographicException) + { + ProfileClient.DataStore.DeleteFile(CacheFileName); + } } } }