using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Cryptography; namespace DigitalData.Core.Application { /// /// Implements the interface to manage JWT operations for claims of type . /// public class JWTService : IJWTService { private readonly Func _factory; /// /// Initializes a new instance of the class. /// /// A factory function to produce based on the claim value. public JWTService(Func tokenDescriptorFactory) { _factory = tokenDescriptorFactory; } /// /// Generates a symmetric security key with the specified byte size. /// /// The size of the security key in bytes. Default is 32 bytes. /// A new instance of . public static SymmetricSecurityKey GenerateSecurityKey(int byteSize = 32) { using var rng = RandomNumberGenerator.Create(); var randomBytes = new byte[byteSize]; rng.GetBytes(randomBytes); var securityKey = new SymmetricSecurityKey(randomBytes); return securityKey; } /// /// Generates a JWT for the specified claim value. /// /// The claim value to encode in the JWT. /// A JWT as a string. public string GenerateToken(TClaimValue claimValue) { var tokenDescriptor = _factory(claimValue); var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } /// /// Reads and validates a security token from a string representation. /// /// The JWT to read. /// A if the token is valid; otherwise, null. public JwtSecurityToken? ReadSecurityToken(string token) { var tokenHandler = new JwtSecurityTokenHandler(); return tokenHandler.CanReadToken(token) ? tokenHandler.ReadToken(token) as JwtSecurityToken : null; } } }