// RB2 Core Connect using System.IdentityModel.Tokens.Jwt;using System.Security.Claims;using System.Text;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.Options;using Microsoft.IdentityModel.Tokens; namespace CoreConnect.Commerce.Customer; public class TokenGeneratorService : ITokenGeneratorService{ private readonly TokenGeneratorOptions _options; public TokenGeneratorService(IOptions<TokenGeneratorOptions> options) { _options = options.Value; } public TokenGeneratorService(IConfigurationSection options) { var tokenOptions = new TokenGeneratorOptions(); options.Bind(tokenOptions); _options = tokenOptions; } public string GenerateJWTToken(IEnumerable<Claim> claims, DateTime? expires = null, bool isRenewal = false) { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.SecurityKey!)); var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( _options.Issuer, _options.Audience + (isRenewal ? " - Renewal" : ""), claims, expires: expires ?? DateTime.Now.AddHours(1), signingCredentials: signingCredentials); return new JwtSecurityTokenHandler().WriteToken(token); } public IEnumerable<Claim> GetJWTClaims(string token) => new JwtSecurityToken(token).Claims; public IEnumerable<Claim>? ValidateRenewalToken(string token) { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.SecurityKey!)); var tokenHandler = new JwtSecurityTokenHandler(); var principal = tokenHandler.ValidateToken(token, new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, IssuerSigningKey = key, ValidIssuer = _options.Issuer, ValidAudience = _options.Audience + " - Renewal", }, out var stok); if (principal == null || !principal.Claims.Any() || stok == null) { return null; } return principal.Claims; }}