using System; using System.Collections.Generic; using System.Linq; using System.Web; using JWT; using JWT.Algorithms; using JWT.Exceptions; using JWT.Serializers; using Newtonsoft.Json; namespace VueWebApi.Tools { public class JwtTools { public static string Key { get; set; } = "Hello World"; //不要泄密 //加密 public static string Encode(Dictionary 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); //添加一个Jwt时效串 payLoad.Add("timeout", DateTime.Now.AddDays(1)); return encoder.Encode(payLoad, key); } //解密 public static Dictionary Decode(string jwtstr, string key = null) { if (string.IsNullOrEmpty(key)) { key = Key; } try { IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm); var json = decoder.Decode(jwtstr, key, verify: true);//token为之前生成的字符串 //string---->Dictionary //把一个字符串反向生成对应的对象内容 var result = JsonConvert.DeserializeObject>(json); if ((DateTime)result["timeout"] < DateTime.Now) { throw new Exception(message:"Jwt已过期,请重新登录"); } result.Remove(key: "timeout"); return result; } catch (TokenExpiredException) { throw; //请求超时 } catch (SignatureVerificationException) { throw; //签名验证失败,数据可能被篡改 } } //校验登录 //public static string key = "123456"; //public static string ValideLogined(HttpRequest req) //{ // if (req.Headers["token"] == null) // throw new Exception(message: "请登录!"); // return Decode(token: req.Headers["token"], key); //} } }