using DealerSelection.Api.CommonUtil; using DealerSelection.Api.Infrastructure.Jwt; using DealerSelection.Api.Interface; using DealerSelection.Api.Models; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; public class JwtTokenApi : IJwtTokenApi { private IJwtRepository Repository { get; } private readonly ILogger _logger; public JwtTokenApi(IJwtRepository repository, ILogger logger) { Repository = repository; _logger = logger; } public async Task GenerateToken(AuthValidateModel user) { try { bool isValidUser = await Authenticate(user); if (isValidUser) { AuthModel auth = new AuthModel { BuId = user.BuId, ClientId = user.ClientId, SecretId = user.SecretId, Role = "Admin" }; CustomCfg cfg = CustomCfg.GetCustomCfg(auth.BuId); var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(cfg.Key)); string expireMinutes = cfg.ExpireMinutes; int tokenExpireMinutes = string.IsNullOrEmpty(expireMinutes) ? 1439 : int.Parse(expireMinutes); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(ClaimTypes.NameIdentifier,auth.ClientId), new Claim(ClaimTypes.Role,auth.Role), }; var token = new JwtSecurityToken( cfg.Issuer, cfg.Audience, claims, expires: DateTime.UtcNow.AddMinutes(tokenExpireMinutes), signingCredentials: credentials); return new JwtSecurityTokenHandler().WriteToken(token); } } catch (Exception ex) { _logger.LogError("JwtTokenApi Api GenerateToken:- " + ex.Message.ToString()); } return null; } public async Task Authenticate(AuthValidateModel userLogin) { try { CustomCfg cfg = CustomCfg.GetCustomCfg(userLogin.BuId); return cfg.ClientId.ToLower() == userLogin.ClientId.ToLower() && cfg.ClientSecret.ToLower() == userLogin.SecretId.ToLower(); } catch (Exception ex) { _logger.LogError("JwtTokenApi Api Authenticate:- " + ex.Message.ToString()); } return false; } public async Task IsTokenExpired(string tokenValue) { TokenValidProperty tokenValid = new TokenValidProperty(); try { var tokenTicks = GetTokenExpirationTime(tokenValue); var tokenDate = DateTimeOffset.FromUnixTimeSeconds(tokenTicks).UtcDateTime; var now = DateTime.UtcNow; var valid = tokenDate >= now; tokenValid.isValid = valid; tokenValid.Ttl = tokenDate.TimeOfDay.TotalSeconds - now.TimeOfDay.TotalSeconds; return tokenValid; } catch (Exception ex) { _logger.LogError("JwtTokenApi Api IsTokenExpired:- " + ex.Message.ToString()); return tokenValid; } } private static long GetTokenExpirationTime(string token) { var handler = new JwtSecurityTokenHandler(); var jwtSecurityToken = handler.ReadJwtToken(token); var tokenExp = jwtSecurityToken.Claims.First(claim => claim.Type.Equals("exp")).Value; var ticks = long.Parse(tokenExp); return ticks; } }