2022-09-26 04:40:18 +03:00
|
|
|
using System;
|
|
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
|
|
using System.Security.Claims;
|
|
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
|
2022-11-18 03:15:53 +03:00
|
|
|
namespace CodeLiturgy.Data.Auth.Context.Users;
|
2022-09-26 04:40:18 +03:00
|
|
|
|
|
|
|
public class JwtTokenHandler : IJwtTokenHandler
|
|
|
|
{
|
|
|
|
private readonly JwtSecurityTokenHandler _jwtSecurityTokenHandler;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// JwtTokenHandler
|
|
|
|
/// </summary>
|
|
|
|
public JwtTokenHandler()
|
|
|
|
{
|
|
|
|
_jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Write token
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="jwt"></param>
|
|
|
|
/// <returns></returns>
|
|
|
|
public string WriteToken(JwtSecurityToken jwt)
|
|
|
|
{
|
|
|
|
return _jwtSecurityTokenHandler.WriteToken(jwt);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Validate Token
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="token"></param>
|
|
|
|
/// <param name="tokenValidationParameters"></param>
|
|
|
|
/// <returns></returns>
|
|
|
|
/// <exception cref="SecurityTokenException"></exception>
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|