forked from NetDevPack/Security.Jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInMemoryStore.cs
More file actions
65 lines (57 loc) · 2.03 KB
/
InMemoryStore.cs
File metadata and controls
65 lines (57 loc) · 2.03 KB
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
using System.Collections.ObjectModel;
using NetDevPack.Security.Jwt.Core.Interfaces;
using NetDevPack.Security.Jwt.Core.Jwa;
using NetDevPack.Security.Jwt.Core.Model;
namespace NetDevPack.Security.Jwt.Core.DefaultStore;
internal class InMemoryStore : IJsonWebKeyStore
{
internal const string DefaultRevocationReason = "Revoked";
private static readonly List<KeyMaterial> _store = new();
private readonly SemaphoreSlim _slim = new(1);
public Task Store(KeyMaterial keyMaterial)
{
_slim.Wait();
_store.Add(keyMaterial);
_slim.Release();
return Task.CompletedTask;
}
public Task<KeyMaterial> GetCurrent(JwtKeyType jwtKeyType)
{
return Task.FromResult(_store.OrderByDescending(s => s.CreationDate).FirstOrDefault());
}
public async Task Revoke(KeyMaterial keyMaterial, string reason = null)
{
if(keyMaterial == null)
return;
var revokeReason = reason ?? DefaultRevocationReason;
keyMaterial.Revoke(revokeReason);
var oldOne = _store.Find(f => f.Id == keyMaterial.Id);
if (oldOne != null)
{
var index = _store.FindIndex(f => f.Id == keyMaterial.Id);
await _slim.WaitAsync();
_store.RemoveAt(index);
_store.Insert(index, keyMaterial);
_slim.Release();
}
}
public Task<ReadOnlyCollection<KeyMaterial>> GetLastKeys(int quantity, JwtKeyType? jwtKeyType)
{
return Task.FromResult(
_store
.Where(s => jwtKeyType == null || s.Use == (jwtKeyType == JwtKeyType.Jws ? "sig" : "enc"))
.OrderByDescending(s => s.CreationDate)
.GroupBy(s => s.Use)
.SelectMany(g => g.Take(quantity))
.ToList().AsReadOnly());
}
public Task<KeyMaterial> Get(string keyId)
{
return Task.FromResult(_store.FirstOrDefault(w => w.KeyId == keyId));
}
public Task Clear()
{
_store.Clear();
return Task.CompletedTask;
}
}