JwtEncryption.cs
2.1 KB
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
using System;
using System.Collections.Generic;
using JWT;
using JWT.Algorithms;
using JWT.Builder;
using JWT.Serializers;
namespace Hh.Mes.Common
{
public class JwtEncryption
{
/// <summary>
/// 默认密钥
/// </summary>
public readonly static string _secret = "1q2w3e4r5t6y";
/// <summary>
/// 解密
/// </summary>
/// <param name="token"></param>
/// <param name="secret"></param>
/// <returns></returns>
public static string Decode(string token, string secret = null)
{
if (string.IsNullOrWhiteSpace(secret))
{
secret = _secret;
}
var serializer = new JsonNetSerializer();
var provider = new UtcDateTimeProvider();
var validator = new JwtValidator(serializer, provider);
var urlEncoder = new JwtBase64UrlEncoder();
var alg = new HMACSHA256Algorithm();
var decoder = new JwtDecoder(serializer, validator, urlEncoder, alg);
//{"loginName":"admin","iss":"dims","exp":1637637033}
return decoder.Decode(token, secret, false);
}
/// <summary>
/// 加密{ "loginName", "tuzhuang" }, { "ISSURE", "hh2.0" },,
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string Encode(Dictionary<string, object> value, string secret = null)
{
if (string.IsNullOrWhiteSpace(secret))
{
secret = _secret;
}
//过期时间
if (!value.ContainsKey("exp"))
{
//有效期1天
value.Add("exp", DateTimeOffset.UtcNow.AddDays(1).ToUnixTimeSeconds().ToString());
}
var algorithm = new HMACSHA256Algorithm();
var serializer = new JsonNetSerializer();
var urlEncoder = new JwtBase64UrlEncoder();
var encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
return encoder.Encode(value, secret);
}
}
}