using AuthApi.Models; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; namespace AuthApi.Services; public class JwtTokenService { private readonly IConfiguration _cfg; public JwtTokenService(IConfiguration cfg) => _cfg = cfg; public (string Token, string Jti, DateTime ExpiresUtc) Generate(User user) { var key = Encoding.UTF8.GetBytes(_cfg["Jwt:Key"] ?? throw new InvalidOperationException("Jwt:Key missing")); var issuer = _cfg["Jwt:Issuer"] ?? "GameAuthApi"; var audience = _cfg["Jwt:Audience"] ?? issuer; var credentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256); var jti = Guid.NewGuid().ToString("N"); var claims = new[] { new Claim(ClaimTypes.Name, user.Username), new Claim(ClaimTypes.NameIdentifier, user.Id), new Claim(ClaimTypes.Role, user.Role), new Claim(JwtRegisteredClaimNames.Jti, jti) }; var expiresUtc = DateTime.UtcNow.AddMinutes(15); var token = new JwtSecurityToken(issuer, audience, claims, expires: expiresUtc, signingCredentials: credentials); return (new JwtSecurityTokenHandler().WriteToken(token), jti, expiresUtc); } }