|
| 1 | +using System.IdentityModel.Tokens.Jwt; |
| 2 | +using System.Security.Claims; |
| 3 | +using System.Text; |
| 4 | +using Microsoft.IdentityModel.Tokens; |
| 5 | +using PaymentCoreServiceApi.Core.Entities.UserAgents; |
| 6 | + |
| 7 | +namespace PaymentCoreServiceApi.Features.Auth; |
| 8 | + |
| 9 | +public interface IJwtService |
| 10 | +{ |
| 11 | + string GenerateToken(User user); |
| 12 | + ClaimsPrincipal? ValidateToken(string token); |
| 13 | +} |
| 14 | + |
| 15 | +public class JwtService : IJwtService |
| 16 | +{ |
| 17 | + private readonly IConfiguration _configuration; |
| 18 | + |
| 19 | + public JwtService(IConfiguration configuration) |
| 20 | + { |
| 21 | + _configuration = configuration; |
| 22 | + } |
| 23 | + |
| 24 | + public string GenerateToken(User user) |
| 25 | + { |
| 26 | + var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]!)); |
| 27 | + var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); |
| 28 | + |
| 29 | + var claims = new[] |
| 30 | + { |
| 31 | + new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), |
| 32 | + new Claim(ClaimTypes.Name, user.UserName), |
| 33 | + new Claim(ClaimTypes.Email, user.Email), |
| 34 | + }; |
| 35 | + |
| 36 | + var token = new JwtSecurityToken( |
| 37 | + issuer: _configuration["Jwt:Issuer"], |
| 38 | + audience: _configuration["Jwt:Audience"], |
| 39 | + claims: claims, |
| 40 | + expires: DateTime.Now.AddHours(1), |
| 41 | + signingCredentials: credentials |
| 42 | + ); |
| 43 | + |
| 44 | + return new JwtSecurityTokenHandler().WriteToken(token); |
| 45 | + } |
| 46 | + |
| 47 | + public ClaimsPrincipal? ValidateToken(string token) |
| 48 | + { |
| 49 | + try |
| 50 | + { |
| 51 | + var tokenHandler = new JwtSecurityTokenHandler(); |
| 52 | + var key = Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]!); |
| 53 | + |
| 54 | + var validationParameters = new TokenValidationParameters |
| 55 | + { |
| 56 | + ValidateIssuerSigningKey = true, |
| 57 | + IssuerSigningKey = new SymmetricSecurityKey(key), |
| 58 | + ValidateIssuer = true, |
| 59 | + ValidateAudience = true, |
| 60 | + ValidIssuer = _configuration["Jwt:Issuer"], |
| 61 | + ValidAudience = _configuration["Jwt:Audience"], |
| 62 | + ClockSkew = TimeSpan.Zero |
| 63 | + }; |
| 64 | + |
| 65 | + return tokenHandler.ValidateToken(token, validationParameters, out _); |
| 66 | + } |
| 67 | + catch |
| 68 | + { |
| 69 | + return null; |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments