CodeLiturgy.Dashboard/BlueWest.Api/Users/Auth/Crypto/JwtTokenHandler.cs

53 lines
1.5 KiB
C#
Raw Normal View History

2022-09-10 00:33:17 +03:00
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;
2022-09-11 01:22:04 +03:00
/// <summary>
/// JwtTokenHandler
/// </summary>
2022-09-10 00:33:17 +03:00
public JwtTokenHandler()
{
2022-09-11 01:22:04 +03:00
_jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
2022-09-10 00:33:17 +03:00
}
2022-09-11 01:22:04 +03:00
/// <summary>
/// Write token
/// </summary>
/// <param name="jwt"></param>
/// <returns></returns>
2022-09-10 00:33:17 +03:00
public string WriteToken(JwtSecurityToken jwt)
{
return _jwtSecurityTokenHandler.WriteToken(jwt);
}
2022-09-11 01:22:04 +03:00
/// <summary>
/// Validate Token
/// </summary>
/// <param name="token"></param>
/// <param name="tokenValidationParameters"></param>
/// <returns></returns>
/// <exception cref="SecurityTokenException"></exception>
2022-09-10 00:33:17 +03:00
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;
}
}
}