Files
ERP_Auth_Service/Utility/JwtTokenHelper.cs
Dhananjaya99 15832d1ae3 Decouple UserType, add Role entity and management
Removed all UserType logic and references, replacing them with a new Role model and management system. Introduced RoleManager service, repository, and API endpoint for role CRUD operations. Updated user flows and JWT claims to use RoleCode. Removed admin-only user CRUD endpoints. Updated DI, documentation, and error handling for consistency. Appsettings and DTOs now reflect the new role-based approach.
2026-10-19 12:57:07 +05:30

86 lines
2.8 KiB
C#

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)
{
var claims = new List<Claim>
{
new Claim("UserId", user.Id.ToString()),
new Claim("RoleId", user.RoleCode ?? ""),
new Claim("RoleCode", user.RoleCode ?? ""),
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;
}
}
}