| | | 1 | | using System.IdentityModel.Tokens.Jwt; |
| | | 2 | | using System.Security.Claims; |
| | | 3 | | using System.Text; |
| | | 4 | | using MechanicsSoftware.Application.Abstractions; |
| | | 5 | | using Microsoft.Extensions.Configuration; |
| | | 6 | | using Microsoft.IdentityModel.Tokens; |
| | | 7 | | using MechanicsSoftware.Domain.Entities; |
| | | 8 | | using MechanicsSoftware.Domain.ValueObjects; |
| | | 9 | | using MechanicsSoftware.Domain.Enums; |
| | | 10 | | using MechanicsSoftware.Domain.Exceptions; |
| | | 11 | | |
| | | 12 | | namespace MechanicsSoftware.Infrastructure.Security; |
| | | 13 | | |
| | | 14 | | public sealed class JwtProvider : IJwtProvider |
| | | 15 | | { |
| | 5 | 16 | | private readonly string _secret; |
| | 5 | 17 | | private readonly int _expirationMinutes; |
| | 5 | 18 | | |
| | 17 | 19 | | public JwtProvider(IConfiguration configuration) |
| | 17 | 20 | | { |
| | 12 | 21 | | _secret = configuration["JWT_SECRET"] |
| | 16 | 22 | | ?? throw new InvalidOperationException( |
| | 16 | 23 | | "JWT secret not configured. Set the 'JWT_SECRET' environment variable."); |
| | 4 | 24 | | |
| | 14 | 25 | | _expirationMinutes = int.TryParse(configuration["JWT_EXPIRATION_MINUTES"], out var minutes) && minutes > 0 |
| | 10 | 26 | | ? minutes |
| | 10 | 27 | | : 60; |
| | 14 | 28 | | } |
| | 4 | 29 | | |
| | | 30 | | public JwtToken Generate(User user) |
| | 14 | 31 | | { |
| | 14 | 32 | | var expiresAt = DateTime.UtcNow.AddMinutes(_expirationMinutes); |
| | 4 | 33 | | |
| | 14 | 34 | | var claims = new[] |
| | 14 | 35 | | { |
| | 14 | 36 | | new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()), |
| | 14 | 37 | | new Claim(JwtRegisteredClaimNames.Email, user.Email.Value), |
| | 10 | 38 | | new Claim(ClaimTypes.Role, user.Role), |
| | 14 | 39 | | new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) |
| | 14 | 40 | | }; |
| | | 41 | | |
| | 14 | 42 | | var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secret)); |
| | 14 | 43 | | var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); |
| | 4 | 44 | | |
| | 14 | 45 | | var token = new JwtSecurityToken( |
| | 10 | 46 | | claims: claims, |
| | 14 | 47 | | expires: expiresAt, |
| | 14 | 48 | | signingCredentials: credentials); |
| | | 49 | | |
| | 10 | 50 | | return new JwtToken(new JwtSecurityTokenHandler().WriteToken(token), expiresAt); |
| | 10 | 51 | | } |
| | | 52 | | } |