yl
2023-09-19 fbba6d6e8ccf4b052735bd51fd04ff7cb5c16b78
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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;
using VueWebCoreApi.Models;
 
namespace VueWebCoreApi.Tools
{
    public static class JwtTools
    {
        public static ToMessage mes = new ToMessage(); //定义全局返回信息对象
        public static string Key = AppSetting.GetAppSetting("SigningKey");
        public static double time =double.Parse(AppSetting.GetAppSetting("RedisKeyTimeCont"));
        //public static string Key { get; set; } = "Hello World"; //不要泄密
        //加密
        public static ToMessage 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.AddSeconds(time));
            mes.code = "200";
            mes.Message = "获取token成功!";
            mes.data= encoder.Encode(payLoad, key);
            return mes;
        }
 
        //解密(数据类型1)
        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: "token已过期,请重新登录");
                }
                result.Remove(key: "timeout");
                return result;
            }
            catch (TokenExpiredException)
            {
 
                throw;  //请求超时
            }
            catch (SignatureVerificationException)
            {
                throw; //签名验证失败,数据可能被篡改
            }
        }
        //解密(数据类型2)
        public static User Denocode(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
                //把一个字符串反向生成对应的对象内容 
                User loginUser = JsonConvert.DeserializeObject<User>(json);
                return loginUser;
            }
            catch (TokenExpiredException)
            {
 
                throw;  //请求超时
            }
            catch (SignatureVerificationException)
            {
                throw; //签名验证失败,数据可能被篡改
            }
        }
 
        //根据给定值获取键名
        public static K FindFirstValueByKey<K, V>(this Dictionary<K, V> dict, V val)
        {
            return dict.FirstOrDefault(entry =>
                EqualityComparer<V>.Default.Equals(entry.Value, val)).Key;
        }
 
        //根据给定键名获取值
        public static V FindFirstKeyByValue<K,V>(this Dictionary<K, V> dict, K val)
        {
            return dict.FirstOrDefault(entry =>EqualityComparer<K>.Default.Equals(entry.Key, val)).Value;
        }
        //校验登录
        //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);
        //}
    }
}