forked from microsoftgraph/aspnet-snippets-sample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSessionTokenCache.cs
78 lines (66 loc) · 2.32 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
/*
* Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.
* See LICENSE in the source repository root for complete license information.
*/
using System.Web;
using Microsoft.Identity.Client;
namespace Microsoft_Graph_ASPNET_Snippets.TokenStorage
{
// Store the user's token information.
public class SessionTokenCache : TokenCache
{
private HttpContextBase context;
private static readonly object FileLock = new object();
private readonly string CacheId = string.Empty;
public string UserObjectId = string.Empty;
public SessionTokenCache(string userId, HttpContextBase context)
{
this.context = context;
this.UserObjectId = userId;
this.CacheId = UserObjectId + "_TokenCache";
AfterAccess = AfterAccessNotification;
BeforeAccess = BeforeAccessNotification;
Load();
}
public void Load()
{
lock (FileLock)
{
Deserialize((byte[])context.Session[CacheId]);
}
}
public void Persist()
{
lock (FileLock)
{
// Reflect changes in the persistent store.
var bytes = Serialize();
var x = System.Text.Encoding.UTF8.GetString(bytes);
context.Session[CacheId] = Serialize();
// After the write operation takes place, restore the HasStateChanged bit to false.
HasStateChanged = false;
}
}
// Empties the persistent store.
public override void Clear(string clientId)
{
base.Clear(clientId);
context.Session.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 (HasStateChanged)
{
Persist();
}
}
}
}