Skip to content

Commit 39afc3c

Browse files
committed
Encrypting the token cache on disk
(best practice)
1 parent d8ad0a2 commit 39afc3c

1 file changed

Lines changed: 11 additions & 5 deletions

File tree

TodoListClient/FileCache.cs

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,9 @@
2525
//
2626
//------------------------------------------------------------------------------
2727

28-
using Microsoft.Identity.Client;
2928
using System.IO;
29+
using System.Security.Cryptography;
30+
using Microsoft.Identity.Client;
3031

3132
namespace TodoListClient
3233
{
@@ -53,7 +54,7 @@ public static TokenCache GetUserCache()
5354
/// <summary>
5455
/// Path to the token cache
5556
/// </summary>
56-
public static string CacheFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location + "msalcache.txt";
57+
public static readonly string CacheFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location + ".msalcache.bin";
5758

5859
private static readonly object FileLock = new object();
5960

@@ -62,7 +63,9 @@ public static void BeforeAccessNotification(TokenCacheNotificationArgs args)
6263
lock (FileLock)
6364
{
6465
args.TokenCache.Deserialize(File.Exists(CacheFilePath)
65-
? File.ReadAllBytes(CacheFilePath)
66+
? ProtectedData.Unprotect(File.ReadAllBytes(CacheFilePath),
67+
null,
68+
DataProtectionScope.CurrentUser)
6669
: null);
6770
}
6871
}
@@ -75,12 +78,15 @@ public static void AfterAccessNotification(TokenCacheNotificationArgs args)
7578
lock (FileLock)
7679
{
7780
// reflect changesgs in the persistent store
78-
File.WriteAllBytes(CacheFilePath, args.TokenCache.Serialize());
81+
File.WriteAllBytes(CacheFilePath,
82+
ProtectedData.Protect(args.TokenCache.Serialize(),
83+
null,
84+
DataProtectionScope.CurrentUser)
85+
);
7986
// once the write operationtakes place restore the HasStateChanged bit to filse
8087
args.TokenCache.HasStateChanged = false;
8188
}
8289
}
8390
}
8491
}
85-
8692
}

0 commit comments

Comments
 (0)