This repository was archived by the owner on Jul 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathSessionTokenCache.cs
80 lines (69 loc) · 1.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using Microsoft.Identity.Client;
namespace MSGraphCalendarViewer.TokenStorage
{
public class SessionTokenCache
{
private static ReaderWriterLockSlim SessionLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
string UserId = string.Empty;
string CacheId = string.Empty;
HttpContextBase httpContext = null;
TokenCache cache = new TokenCache();
public SessionTokenCache(string userId, HttpContextBase httpcontext)
{
UserId = userId;
CacheId = UserId + "_TokenCache";
httpContext = httpcontext;
Load();
}
public TokenCache GetMsalCacheInstance()
{
cache.SetBeforeAccess(BeforeAccessNotification);
cache.SetAfterAccess(AfterAccessNotification);
Load();
return cache;
}
public void SaveUserStateValue(string state)
{
SessionLock.EnterWriteLock();
httpContext.Session[CacheId + "_state"] = state;
SessionLock.ExitWriteLock();
}
public string ReadUserStateValue()
{
string state = string.Empty;
SessionLock.EnterReadLock();
state = (string)httpContext.Session[CacheId + "_state"];
SessionLock.ExitReadLock();
return state;
}
public void Load()
{
SessionLock.EnterReadLock();
cache.Deserialize((byte[])httpContext.Session[CacheId]);
SessionLock.ExitReadLock();
}
public void Persist()
{
SessionLock.EnterWriteLock();
cache.HasStateChanged = false;
httpContext.Session[CacheId] = cache.Serialize();
SessionLock.ExitWriteLock();
}
void BeforeAccessNotification(TokenCacheNotificationArgs args)
{
Load();
}
void AfterAccessNotification(TokenCacheNotificationArgs args)
{
if (cache.HasStateChanged)
{
Persist();
}
}
}
}