| | | 1 | | using Anichron.API.Settings; |
| | | 2 | | using Anichron.Core.Domain; |
| | | 3 | | using Microsoft.Extensions.Options; |
| | | 4 | | using Microsoft.IdentityModel.Tokens; |
| | | 5 | | using System.IdentityModel.Tokens.Jwt; |
| | | 6 | | using System.Security.Claims; |
| | | 7 | | using System.Text; |
| | | 8 | | |
| | | 9 | | namespace Anichron.API.Security; |
| | | 10 | | |
| | | 11 | | public interface IJwtFactory |
| | | 12 | | { |
| | | 13 | | string Create(User user); |
| | | 14 | | } |
| | | 15 | | |
| | | 16 | | public sealed class JwtFactory : IJwtFactory |
| | | 17 | | { |
| | | 18 | | private readonly JwtSettings settings; |
| | | 19 | | private readonly IClock clock; |
| | | 20 | | private readonly IGuidFactory guidFactory; |
| | | 21 | | private readonly SigningCredentials credentials; |
| | 1 | 22 | | private static readonly JwtSecurityTokenHandler tokenHandler = new(); |
| | | 23 | | |
| | 12 | 24 | | public JwtFactory(IOptions<JwtSettings> options, IClock clock, IGuidFactory guidFactory) |
| | 12 | 25 | | { |
| | 12 | 26 | | settings = options.Value; |
| | 12 | 27 | | this.clock = clock; |
| | 12 | 28 | | this.guidFactory = guidFactory; |
| | | 29 | | |
| | 12 | 30 | | var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.Secret)); |
| | 12 | 31 | | credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); |
| | 12 | 32 | | } |
| | | 33 | | |
| | | 34 | | public string Create(User user) |
| | 12 | 35 | | { |
| | 12 | 36 | | var claims = new List<Claim> |
| | 12 | 37 | | { |
| | 12 | 38 | | new(JwtRegisteredClaimNames.Sub, user.Id.ToString()), |
| | 12 | 39 | | new(JwtRegisteredClaimNames.UniqueName, user.Username), |
| | 12 | 40 | | new(JwtRegisteredClaimNames.Jti, guidFactory.NewGuid().ToString()), |
| | 12 | 41 | | }; |
| | | 42 | | |
| | 12 | 43 | | if (user.MustChangePassword) |
| | 1 | 44 | | claims.Add(new Claim(AppClaimTypes.MustChangePassword, "true")); |
| | | 45 | | |
| | 12 | 46 | | if (user.IsAdmin) |
| | 1 | 47 | | claims.Add(new Claim(AppClaimTypes.IsAdmin, "true")); |
| | | 48 | | |
| | 12 | 49 | | var token = new JwtSecurityToken( |
| | 12 | 50 | | issuer: settings.Issuer, |
| | 12 | 51 | | audience: settings.Audience, |
| | 12 | 52 | | claims: claims, |
| | 12 | 53 | | expires: clock.GetCurrentInstant().ToDateTimeUtc().AddMinutes(settings.AccessTokenMinutes), |
| | 12 | 54 | | signingCredentials: credentials); |
| | | 55 | | |
| | 12 | 56 | | return tokenHandler.WriteToken(token); |
| | 12 | 57 | | } |
| | | 58 | | } |