add Cache.cs

fix hardware hash stack in the jwt token claims
This commit is contained in:
Alex Bezdieniezhnykh
2025-01-18 14:36:50 +02:00
parent 0945635a1c
commit 49de0351c1
7 changed files with 77 additions and 33 deletions
+16 -21
View File
@@ -11,31 +11,28 @@ namespace Azaion.Services;
public interface IAuthService
{
User? CurrentUser { get; }
Guid? GetCurrentUserId();
Task<User?> GetCurrentUser();
string CreateToken(User user);
}
public class AuthService(IHttpContextAccessor httpContextAccessor, IOptions<JwtConfig> jwtConfig) : IAuthService
public class AuthService(IHttpContextAccessor httpContextAccessor, IOptions<JwtConfig> jwtConfig, IUserService userService) : IAuthService
{
public User? CurrentUser
public Guid? GetCurrentUserId()
{
get
{
var claims = httpContextAccessor.HttpContext?.User.Claims.ToDictionary(x => x.Type);
if (claims == null)
return null;
var claims = httpContextAccessor.HttpContext?.User.Claims.ToDictionary(x => x.Type);
if (claims == null)
return null;
if (!Enum.TryParse(claims[ClaimTypes.Role].Value, out RoleEnum role))
throw new ApplicationException("Invalid role");
var id = Guid.Parse(claims[ClaimTypes.NameIdentifier].Value);
return id;
}
return new User
{
Id = Guid.Parse(claims[ClaimTypes.NameIdentifier].Value),
Email = claims[ClaimTypes.Name].Value,
Role = role,
HardwareHash = claims[Constants.HARDWARE_ID].Value,
};
}
public async Task<User?> GetCurrentUser()
{
var id = GetCurrentUserId();
return await userService.GetById(id);
}
public string CreateToken(User user)
@@ -47,9 +44,7 @@ public class AuthService(IHttpContextAccessor httpContextAccessor, IOptions<JwtC
{
Subject = new ClaimsIdentity([
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Email),
new Claim(ClaimTypes.Role, user.Role.ToString()),
new Claim(Constants.HARDWARE_ID, user.HardwareHash ?? "")
new Claim(ClaimTypes.Role, user.Role.ToString())
]),
Expires = DateTime.UtcNow.AddHours(jwtConfig.Value.TokenLifetimeHours),
Issuer = jwtConfig.Value.Issuer,