This repository has been archived by the owner on Apr 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 96
/
SessionTokenCache.cs
102 lines (88 loc) · 2.89 KB
/
SessionTokenCache.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
* Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.
* See LICENSE in the source repository root for complete license information.
*/
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Identity.Client;
using System.Text;
namespace MicrosoftGraphAspNetCoreConnectSample.Helpers
{
// Store the user's token information.
public class SessionTokenCache
{
private static readonly object FileLock = new object();
private readonly string _cacheId;
private readonly IMemoryCache _memoryCache;
private TokenCache _cache = new TokenCache();
public SessionTokenCache(string userId, IMemoryCache memoryCache)
{
// not object, we want the SUB
_cacheId = userId + "_TokenCache";
_memoryCache = memoryCache;
Load();
}
public TokenCache GetCacheInstance()
{
_cache.SetBeforeAccess(BeforeAccessNotification);
_cache.SetAfterAccess(AfterAccessNotification);
Load();
return _cache;
}
public void SaveUserStateValue(string state)
{
lock (FileLock)
{
_memoryCache.Set(_cacheId + "_state", Encoding.ASCII.GetBytes(state));
}
}
public string ReadUserStateValue()
{
string state;
lock (FileLock)
{
state = Encoding.ASCII.GetString(_memoryCache.Get(_cacheId + "_state") as byte[]);
}
return state;
}
public void Load()
{
lock (FileLock)
{
_cache.Deserialize(_memoryCache.Get(_cacheId) as byte[]);
}
}
public void Persist()
{
lock (FileLock)
{
// reflect changes in the persistent store
_memoryCache.Set(_cacheId, _cache.Serialize());
// once the write operation took place, restore the HasStateChanged bit to false
_cache.HasStateChanged = false;
}
}
// Empties the persistent store.
public void Clear()
{
_cache = null;
lock (FileLock) {
_memoryCache.Remove(_cacheId);
}
}
// Triggered right before MSAL needs to access the cache.
// Reload the cache from the persistent store in case it changed since the last access.
private void BeforeAccessNotification(TokenCacheNotificationArgs args)
{
Load();
}
// Triggered right after MSAL accessed the cache.
private void AfterAccessNotification(TokenCacheNotificationArgs args)
{
// if the access operation resulted in a cache update
if (_cache.HasStateChanged)
{
Persist();
}
}
}
}