using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
public class JwtTokenParser
{
private readonly string _secretKey;
public JwtTokenParser(string secretKey)
{
_secretKey = secretKey;
}
public bool TryParseToken(string token, out Payload payload)
{
payload = null;
var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secretKey)),
ValidateIssuer = false,
ValidateAudience = false
};
try
{
ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);
payload = new Payload
{
UserId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value,
Roles = claimsPrincipal.FindAll(ClaimTypes.Role)?.Select(claim => claim.Value).ToList()
};
return true;
}
catch (Exception)
{
return false;
}
}
}
public class Payload
{
public string UserId { get; set; }
public List<string> Roles { get; set; }
}