72 lines
2.7 KiB
C#
72 lines
2.7 KiB
C#
|
|
using System;
|
|||
|
|
using System.Collections.Generic;
|
|||
|
|
using System.Linq;
|
|||
|
|
using System.Web;
|
|||
|
|
using JWT;
|
|||
|
|
using JWT.Algorithms;
|
|||
|
|
using JWT.Serializers;
|
|||
|
|
using Newtonsoft.Json;
|
|||
|
|
|
|||
|
|
namespace Services.Tool
|
|||
|
|
{
|
|||
|
|
/// <summary>
|
|||
|
|
/// Token辅助类
|
|||
|
|
/// 需要引用jwt包
|
|||
|
|
/// </summary>
|
|||
|
|
public class TokenHelper
|
|||
|
|
{
|
|||
|
|
//私钥
|
|||
|
|
static string Private_key = "CWLCJLWQZYY";
|
|||
|
|
//创建一个世界协调时间提供对象 utc时间协调时间
|
|||
|
|
static IDateTimeProvider provider = new UtcDateTimeProvider();
|
|||
|
|
//时间戳起点时间
|
|||
|
|
static DateTime timeEpoch = new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc);
|
|||
|
|
//序列化对象
|
|||
|
|
static IJsonSerializer serializer = new JsonNetSerializer();
|
|||
|
|
//编码序列化对象
|
|||
|
|
static IBase64UrlEncoder encoder = new JwtBase64UrlEncoder();
|
|||
|
|
//编码算法
|
|||
|
|
static IJwtAlgorithm algorithm = new HMACSHA384Algorithm();
|
|||
|
|
//jwt编码
|
|||
|
|
static JwtEncoder jwtEncoder= new JwtEncoder(algorithm,serializer,encoder);
|
|||
|
|
//验证对象
|
|||
|
|
static IJwtValidator validator = new JwtValidator(serializer,provider);
|
|||
|
|
//jwt解码
|
|||
|
|
static JwtDecoder decoder = new JwtDecoder(serializer, validator, encoder, algorithm);
|
|||
|
|
/// <summary>
|
|||
|
|
/// 加密的数据键值对传入
|
|||
|
|
/// </summary>
|
|||
|
|
/// <param name="keys"></param>
|
|||
|
|
/// <returns></returns>
|
|||
|
|
public static string GetToken(Dictionary<string,object> keys,float day)
|
|||
|
|
{
|
|||
|
|
//荷载,负载,最重要的信息,token中保存的信息 keys
|
|||
|
|
var now = provider.GetNow();
|
|||
|
|
//获取当前时间距离时间戳的差秒
|
|||
|
|
var epochSecons = Math.Round((now-timeEpoch).TotalSeconds);
|
|||
|
|
keys.Add("exp",(epochSecons+3600)*24*day);//设置过期时间
|
|||
|
|
//jwt同一加密
|
|||
|
|
var token = jwtEncoder.Encode(keys,Private_key);
|
|||
|
|
return token;
|
|||
|
|
}
|
|||
|
|
public static string CheckToken(string token)
|
|||
|
|
{
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
//解码 tonken 私钥 验证是否过期
|
|||
|
|
//过期时间验证 系统默认起始时间为1970,1,1,0,0,0 如果验证过期需要保证起始时间一致
|
|||
|
|
//要么手动验证过期,现在时间与起始时间的差值如果大于设置exp则过期
|
|||
|
|
return JsonConvert.DeserializeObject<Datainfo>(decoder.Decode(token, Private_key,verify: true)).data.ToString();//str数据转成Dictionary<string,object>类型即可
|
|||
|
|
}
|
|||
|
|
catch (Exception)
|
|||
|
|
{
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
}
|
|||
|
|
public class Datainfo {
|
|||
|
|
public dynamic data { get; set; }
|
|||
|
|
public dynamic exp { get; set; }
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|