Created
May 29, 2020 21:29
-
-
Save manoj-choudhari-git/75b48ce346a98eddc583362fbc2be600 to your computer and use it in GitHub Desktop.
Static class for Token Cache implementation for WPF Application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static class TokenCacheHelper | |
{ | |
/// <summary> | |
/// Path to the token cache | |
/// </summary> | |
public static readonly string CacheFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location + ".msalcache.bin"; | |
private static readonly object FileLock = new object(); | |
public static void BeforeAccessNotification(TokenCacheNotificationArgs args) | |
{ | |
lock (FileLock) | |
{ | |
args.TokenCache.DeserializeMsalV3(File.Exists(CacheFilePath) | |
? ProtectedData.Unprotect(File.ReadAllBytes(CacheFilePath), | |
null, | |
DataProtectionScope.CurrentUser) | |
: null); | |
} | |
} | |
public static void AfterAccessNotification(TokenCacheNotificationArgs args) | |
{ | |
// if the access operation resulted in a cache update | |
if (args.HasStateChanged) | |
{ | |
lock (FileLock) | |
{ | |
// reflect changesgs in the persistent store | |
File.WriteAllBytes(CacheFilePath, | |
ProtectedData.Protect(args.TokenCache.SerializeMsalV3(), | |
null, | |
DataProtectionScope.CurrentUser)); | |
} | |
} | |
} | |
internal static void Bind(ITokenCache tokenCache) | |
{ | |
tokenCache.SetBeforeAccess(BeforeAccessNotification); | |
tokenCache.SetAfterAccess(AfterAccessNotification); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment