Jwt 算法的封装

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;
    }
}
posted @ 2023-02-21 21:26  蜗牛向海  阅读(33)  评论(0编辑  收藏  举报