This commit is contained in:
Dhananjaya99
2026-07-08 11:11:50 +05:30
parent 2cd2741f77
commit de7b40a147
51 changed files with 6839 additions and 0 deletions
+101
View File
@@ -0,0 +1,101 @@
using AuthHex;
using AuthHex.Models;
using AuthHex.Utility;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
namespace AuthSystem.API.Utils;
public class JwtTokenHelper
{
private readonly IConfiguration _config;
private readonly AppDBContext _dbContext;
private readonly RsaKeyProvider _rsaKeyProvider;
public JwtTokenHelper(IConfiguration config, AppDBContext dbContext, RsaKeyProvider rsaKeyProvider)
{
_config = config;
_dbContext = dbContext;
_rsaKeyProvider = rsaKeyProvider;
}
public async Task<string> GenerateToken(User user)
{
// Load user's role and usertype if not already loaded
if (user.Role == null)
{
await _dbContext.Entry(user)
.Reference(u => u.Role)
.LoadAsync();
}
if (user.UserType == null)
{
await _dbContext.Entry(user)
.Reference(u => u.UserType)
.LoadAsync();
}
var claims = new List<Claim>
{
new Claim("UserId", user.Id.ToString()),
new Claim("UserTypeId", user.UserTypeId.ToString()),
new Claim("UserTypeCode", user.UserType?.Code ?? ""),
new Claim("RoleId", user.RoleId.ToString()),
new Claim("RoleCode", user.Role?.Code ?? ""),
new Claim("NIC", user.Nic ?? ""),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat,
new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString(),
ClaimValueTypes.Integer64)
};
var privateKey = _rsaKeyProvider.GetPrivateKey();
var creds = new SigningCredentials(privateKey, SecurityAlgorithms.RsaSha256);
var token = new JwtSecurityToken(
issuer: _config["Jwt:Issuer"],
audience: _config["Jwt:Audience"],
claims: claims,
expires: DateTime.UtcNow.AddMinutes(Convert.ToDouble(_config["Jwt:ExpiresInMinutes"]!)),
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
public Guid ExtractUserIdFromToken(string token)
{
try
{
var tokenHandler = new JwtSecurityTokenHandler();
var publicKey = _rsaKeyProvider.GetPublicKey();
tokenHandler.ValidateToken(token, new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = publicKey,
ValidateIssuer = true,
ValidIssuer = _config["Jwt:Issuer"],
ValidateAudience = true,
ValidAudience = _config["Jwt:Audience"],
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
}, out SecurityToken validatedToken);
var jwtToken = (JwtSecurityToken)validatedToken;
var userIdClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == "UserId");
if (userIdClaim != null && Guid.TryParse(userIdClaim.Value, out Guid userId))
{
return userId;
}
return Guid.Empty;
}
catch
{
return Guid.Empty;
}
}
}