JWT加密解密方法

      public static string Key { get; set; } = "123456789987654321";//解密串        
        /// <summary>        
        /// 加密方法         
        /// </summary>         
        /// <param name="payload">需要加密的字典</param>      
        /// <param name="key"></param>     
        /// <returns></returns>        
        public static string Encoder(Dictionary<string, object> payload, string key = null)
        {
            if (string.IsNullOrEmpty(key))
            {

                key = Key;
            }

            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();

            IJsonSerializer serializer = new JsonNetSerializer();

            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();

            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

            //设置失效时间

            payload.Add("timeout", DateTime.Now.AddMinutes(3));

            return encoder.Encode(payload, key);

        }

        /// <summary>            
        /// 解密方法       
        /// </summary>         
        /// <param name="jwtStr"></param>        
        /// <param name="key"></param>           
        /// <returns></returns>           
        public static Dictionary<string, object> Decode(string jwtStr, string key = null)
        {
            if (string.IsNullOrEmpty(key))
            {
                key = Key;
            }
            try
            {
                IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//HMACSHA256加密

                IJsonSerializer serializer = new JsonNetSerializer();

                IDateTimeProvider provider = new UtcDateTimeProvider();

                IJwtValidator validator = new JwtValidator(serializer, provider);

                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();

                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);

                var json = decoder.Decode(jwtStr, key, true);

                //把字符串反向生成对应的对象类              
                var result = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
                if ((DateTime)result["timeout"] < DateTime.Now)
                {
                    result.Remove(key: "timeout");
                    throw new Exception(message: "jwt已经过期,请重新登陆");
                }

                return result;
            }
            catch (TokenExpiredException)
            {

                throw new Exception(message: "Token has expired");

            }
            catch (SignatureVerificationException)
            {

                throw new Exception(message: "Token has invalid signature");

            }

        }

        public static string CheckHeardTocken(HttpRequest request)      
        {
            if (request.Headers["token"]==null)
            {
                throw new Exception("请登录");
            }
           return Newtonsoft.Json.JsonConvert.SerializeObject( Decode(request.Headers["token"]));        
        }

  

posted @ 2021-02-10 16:15  后跳  阅读(1718)  评论(0编辑  收藏  举报