| | | 1 | | using KT.Domain; |
| | | 2 | | using KT.Modules.Security.Core.Application.Contracts; |
| | | 3 | | using KT.Modules.Security.Core.Domain; |
| | | 4 | | using KT.Modules.Security.Core.Domain.Ports; |
| | | 5 | | using Microsoft.Extensions.Configuration; |
| | | 6 | | using Microsoft.IdentityModel.Tokens; |
| | | 7 | | using System.IdentityModel.Tokens.Jwt; |
| | | 8 | | using System.Security.Claims; |
| | | 9 | | using System.Text; |
| | | 10 | | |
| | | 11 | | namespace KT.Modules.Security.Core.Application |
| | | 12 | | { |
| | 3 | 13 | | internal class AccessTokenService(IConfiguration configuration, IRefreshTokenRespository refreshTokenRespository) : |
| | | 14 | | { |
| | | 15 | | public string GenerateAccessToken(User user) |
| | 2 | 16 | | { |
| | 2 | 17 | | var jwtSettings = configuration.GetSection("Jwt"); |
| | 2 | 18 | | var key = Encoding.UTF8.GetBytes(jwtSettings["Key"]!); |
| | | 19 | | |
| | 1 | 20 | | var claims = new[] |
| | 1 | 21 | | { |
| | 1 | 22 | | new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()), |
| | 1 | 23 | | new Claim(JwtRegisteredClaimNames.Name, user.Username), |
| | 1 | 24 | | new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), |
| | 1 | 25 | | new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()) |
| | 1 | 26 | | }; |
| | | 27 | | |
| | 1 | 28 | | var creds = new SigningCredentials( |
| | 1 | 29 | | new SymmetricSecurityKey(key), |
| | 1 | 30 | | SecurityAlgorithms.HmacSha256); |
| | | 31 | | |
| | 1 | 32 | | var token = new JwtSecurityToken( |
| | 1 | 33 | | issuer: jwtSettings["Issuer"], |
| | 1 | 34 | | audience: jwtSettings["Audience"], |
| | 1 | 35 | | claims: claims, |
| | 1 | 36 | | expires: DateTime.UtcNow.AddMinutes(double.Parse(jwtSettings["AccessTokenExpirationMinutes"]!)), |
| | 1 | 37 | | signingCredentials: creds); |
| | | 38 | | |
| | 1 | 39 | | return new JwtSecurityTokenHandler().WriteToken(token); |
| | 1 | 40 | | } |
| | | 41 | | public async Task<RefreshToken> GenerateRefreshTokenAsync(User user) |
| | 1 | 42 | | { |
| | 1 | 43 | | var expires = DateTime.UtcNow.AddDays(double.Parse(configuration["Jwt:RefreshTokenExpirationDays"]!)); |
| | 1 | 44 | | var refreshToken = new RefreshToken( |
| | 1 | 45 | | id: Guid.NewGuid().ToString(), |
| | 1 | 46 | | token: Guid.NewGuid().ToString(), |
| | 1 | 47 | | userId: user.Id, |
| | 1 | 48 | | expires: expires |
| | 1 | 49 | | ); |
| | | 50 | | |
| | 1 | 51 | | await refreshTokenRespository.SaveRefreshToken(refreshToken); |
| | 1 | 52 | | return refreshToken; |
| | 1 | 53 | | } |
| | | 54 | | } |
| | | 55 | | } |