1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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<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);
            //添加一个Jwt时效串
            payLoad.Add("timeout", DateTime.Now.AddDays(1));
            return encoder.Encode(payLoad, key);
        }
 
        //解密
        public static Dictionary<string, object> 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<Dictionary<string, object>>(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);
        //}
    }
}