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"])); }