using JWT.Algorithms;
using JWT.Builder;
using JWT.Exceptions;
using Org.BouncyCastle.Asn1.Pkcs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WMS.Util;
namespace WMS.BZUtil
{
public interface IOperator
{
///
/// 生成jwt令牌
///
/// 用户id
/// 用户名称
/// 用户账号
///
string EncodeToken(string userId, string userName, string account, string EncryptTokenNo, string warehouseNo);
///
/// 解密jwt令牌
///
/// 令牌
/// TokenExpiredException 时间过期,SignatureVerificationException 签证不正确
string DecodeToken(string token);
}
public class Operator : IOperator
{
///
/// 生成jwt令牌
///
/// 用户id
/// 用户名称
/// 用户账号
///
public string EncodeToken(string userId, string userName, string account,string EncryptTokenNo,string warehouseNo)
{
var token = new JwtBuilder()
.WithAlgorithm(new HMACSHA256Algorithm())
.WithSecret(ConfigHelper.GetConfig().JwtSecret)
.AddClaim("iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds())
.AddClaim("exp", DateTimeOffset.UtcNow.AddHours(ConfigHelper.GetConfig().JwtExp).ToUnixTimeSeconds()) // 设置12小时过期
.AddClaim("UserId", userId).AddClaim("UserName", userName).AddClaim("Account", account).AddClaim("EncryptTokenNo", EncryptTokenNo).AddClaim("WarehouseNo", warehouseNo)
.Encode();
return token;
}
///
/// 解密jwt令牌
///
/// 令牌
/// TokenExpiredException 时间过期,SignatureVerificationException 签证不正确
public string DecodeToken(string token)
{
try
{
var json = new JwtBuilder()
.WithAlgorithm(new HMACSHA256Algorithm())
.WithSecret(ConfigHelper.GetConfig().JwtSecret)
.MustVerifySignature()
.Decode(token);
return json;
//Console.WriteLine(json);
}
catch (TokenExpiredException)
{
return "TokenExpiredException";
//Console.WriteLine("Token has expired");
}
catch (SignatureVerificationException)
{
return "SignatureVerificationException";
//Console.WriteLine("Token has invalid signature");
}
}
}
///
/// 令牌中的信息
///
public class Payload
{
///
/// 用户Id
///
public string UserId { get; set; }
///
/// 用户名称
///
public string UserName { get; set; }
///
/// 用户账号
///
public string Account { get; set; }
public string WarehouseNo { get; set; }
public string EncryptTokenNo { get; set; }
}
}