Skip to content

Instantly share code, notes, and snippets.

@hoetz
Created December 31, 2017 17:48
Show Gist options
  • Save hoetz/90498a37fd9f3b9ac586004b30d9566a to your computer and use it in GitHub Desktop.
Save hoetz/90498a37fd9f3b9ac586004b30d9566a to your computer and use it in GitHub Desktop.
Naive MSAL TokenCache in F#
//based on https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/blob/90dca9e8a28102d7eb0d96d70e93350f5a0e095a/samples/desktop/SampleApp/CachePersistence.cs
module MicrosoftIdentityUtil
open Microsoft.Identity.Client
open System.IO
type CachePersistence() =
static let fileLock = new obj()
static let usertokenCache = new TokenCache()
static let cacheFilePath =
System.Reflection.Assembly.GetExecutingAssembly().Location
+ "msalcache.txt"
static let BeforeAccessNotification =
TokenCache.TokenCacheNotification(fun args ->
lock fileLock (fun () ->
let readContent =
if File.Exists(cacheFilePath) then
File.ReadAllBytes(cacheFilePath)
else null
args.TokenCache.Deserialize(readContent)))
static let AfterAccessNotification =
TokenCache.TokenCacheNotification(fun args ->
if args.TokenCache.HasStateChanged
then
lock fileLock (fun () ->
File.WriteAllBytes(cacheFilePath, args.TokenCache.Serialize())
args.TokenCache.HasStateChanged<- false
))
static member getUserCache() =
lock fileLock (fun () ->
usertokenCache.SetBeforeAccess(BeforeAccessNotification)
usertokenCache.SetAfterAccess(AfterAccessNotification)
usertokenCache)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment