using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using Microsoft.IdentityModel.Tokens; namespace BlueWest.WebApi.Context.Users; public class JwtTokenHandler : IJwtTokenHandler { private readonly JwtSecurityTokenHandler _jwtSecurityTokenHandler; /// /// JwtTokenHandler /// public JwtTokenHandler() { _jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); } /// /// Write token /// /// /// public string WriteToken(JwtSecurityToken jwt) { return _jwtSecurityTokenHandler.WriteToken(jwt); } /// /// Validate Token /// /// /// /// /// public ClaimsPrincipal ValidateToken(string token, TokenValidationParameters tokenValidationParameters) { try { var principal = _jwtSecurityTokenHandler.ValidateToken(token, tokenValidationParameters, out var securityToken); if (!(securityToken is JwtSecurityToken jwtSecurityToken) || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) throw new SecurityTokenException("Invalid token"); return principal; } catch (Exception e) { return null; } } }