2025-03-28 09:49:56 +08:00

96 lines
3.3 KiB
C#

using ArchivesSystem.Dto.Authorizations;
using JWT;
using JWT.Algorithms;
using JWT.Exceptions;
using JWT.Serializers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EShang.Common
{
public class JwtHelper
{
//私钥 web.config中配置
//yhswArchives 采用md5加密大写;
private static string secret = "07A8DC7AD56AE9C8E3598ECADFB023FF";
/// <summary>
/// 生成JwtToken
/// </summary>
/// <param name="payload">不敏感的用户数据</param>
/// <returns></returns>
public static string BuildJwtToken(string userNo,string userName)
{
//格式如下
IDateTimeProvider provider = new UtcDateTimeProvider();
var now = provider.GetNow();
var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
//过期时间
var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds);
var payload = new Dictionary<string, object>
{
{ "exp", secondsSinceEpoch+3600 }, //3600秒后过期
{ "userNo",userNo },
{ "userName",userName },
{ "AddTokenTime",DateTime.Now }
};
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
var token = encoder.Encode(payload, secret);
return token;
}
/// <summary>
/// 根据jwtToken 获取实体
/// </summary>
/// <param name="token">jwtToken</param>
/// <returns></returns>
public static JwtTokenDto SerializeJwt(string token)
{
try
{
IJsonSerializer serializer = new JsonNetSerializer();
IDateTimeProvider provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider);
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
var algorithm = new HMACSHA256Algorithm();
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
//token为之前生成的字符串
var userInfo = decoder.DecodeToObject(token, secret, verify: true);
//此处json为IDictionary<string, object> 类型
string userNo = userInfo["userNo"].ToString(); //可获取当前用户工号
string userName = userInfo["userName"].ToString(); //可获取当前用户名称
var tm = new JwtTokenDto
{
UserNo = userNo,
UserName = userName
};
return tm;
}
catch (TokenExpiredException)
{
throw new Exception("Token has expired");
}
catch (SignatureVerificationException)
{
throw new Exception("Token has invalid signature");
}
catch (Exception ex)
{
throw ex;
}
}
}
}