-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJWTAuthenticationManager.cs
88 lines (77 loc) · 3.03 KB
/
JWTAuthenticationManager.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
using System.Collections.Concurrent;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Spacebar.ConfigModel;
using Spacebar.DbModel;
using Spacebar.DbModel.Entities;
using Microsoft.IdentityModel.Tokens;
namespace Spacebar.Util;
public class JwtAuthenticationManager
{
private static readonly ConcurrentDictionary<string, User> _users = new();
private readonly DbModel.Db _db;
private readonly string _tokenKey = Config.Instance.Security.JwtSecret;
public JwtAuthenticationManager(DbModel.Db db)
{
_db = db;
}
public async Task<User> GetUserFromToken(string token, DbModel.Db? db = null)
{
db ??= _db;
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_tokenKey);
var validationParameters = new TokenValidationParameters()
{
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidateAudience = false,
ValidateIssuer = false
};
var tokenClaim = tokenHandler.ValidateToken(token, validationParameters, out var tokenValidated);
User? user;
var userId = tokenClaim.Identity?.Name ?? (tokenValidated as JwtSecurityToken)?.Claims.Where(x=>x.Type == "name").Select(x=>x.Value).FirstOrDefault();
if (_users.ContainsKey(userId))
{
user = _users[userId];
Console.WriteLine($"User {user.Id} found in cache!");
}
else
{
user = await db.Users.FirstOrDefaultAsync(x => x.Id == userId);
Console.WriteLine($"User {user?.Id} not found in cache, fetching from db");
_users.TryAdd(user.Id, user);
}
if (_users.Count > Config.Instance.Gateway.AuthCacheSize)
{
Console.WriteLine("Auth cache full, removing oldest user");
_users.TryRemove(user.Id, out _);
}
if (user == null) throw new Exception("User not found");
return user;
}
public string? Authenticate(string username, string password)
{
var user = _db.Users.FirstOrDefault(x => x.Email == username);
if (user == null) return null;
if (!BCrypt.Net.BCrypt.Verify(password, user.Data.Hash)) return null;
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_tokenKey);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new(ClaimTypes.Name, user.Id)
}),
Expires = DateTime.UtcNow.AddDays(30),
IssuedAt = DateTime.UtcNow,
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}