public class JwtEncode
{
/// <summary>
/// 获取token
/// </summary>
/// <param name="args"></param>
/// <returns>token</returns>
/// <exception cref="ArgumentException"></exception>
public static string JwtEncoding(Dictionary<string, object> args)
{
var payload = args.Count == 0 ? throw new ArgumentException($"{nameof(args)}长度为0") : args;
var secret = ConfigurationManager.AppSettings["Jwt"];
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
var token = encoder.Encode(payload, secret);
return token;
}
/// <summary>
/// 解token
/// </summary>
/// <param name="token">token</param>
/// <returns></returns>
public static Dictionary<string, object> JwtDecoding(string token)
{
Dictionary<string, object> data = null;
try
{
var secret = ConfigurationManager.AppSettings["Jwt"];
var serializer = new JsonNetSerializer();
var algorithm = new HMACSHA256Algorithm();
IDateTimeProvider provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider);
var urlEncoder = new JwtBase64UrlEncoder();
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
var json = decoder.Decode(token, secret, verify: true);
data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
}
catch (TokenExpiredException)
{
Console.WriteLine("Token has expired");
return null;
}
catch (SignatureVerificationException)
{
Console.WriteLine("Token has invalid signature");
return null;
}
catch (Exception e)
{
return null;
}
return data;
}
}