using JWT.Algorithms; using JWT.Builder; using JWT.Exceptions; using learun.util; using System; namespace learun.operat { /// /// 版 本 EasyCode EC管理后台 /// Copyright (c) 2019-present EC管理有限公司 /// 创建人:tobin /// 日 期:2019.09.12 /// 描 述:当前连接用户信息处理类 /// public class Operator : IOperator { //private readonly ICache _cache; //public Operator(ICache cache) { // _cache = cache; //} ///// ///// 判断是否登录 ///// ///// 账号 ///// token ///// //public async Task IsOnLine(string account,string token) //{ // try // { // string accountTmp = await _cache.ReadAsync(token); // if (account == accountTmp) // { // return true; // } // else { // return false; // } // } // catch (Exception) // { // return false; // } //} ///// ///// 添加登录者(保存一天时间) ///// ///// 账号 ///// //public async Task AddLoginUser(string account) { // string token = Guid.NewGuid().ToString(); // TimeSpan ts = new TimeSpan(1, 0, 0, 0); // var list = await _cache.ReadAsync>(account); // if (list == null) { // list = new List(); // } // list.Add(token); // await _cache.WriteAsync(account, list, ts); // await _cache.WriteAsync(token, account, ts); // return token; //} ///// ///// 清除登录者信息 ///// ///// 登录者用户账号 ///// //public async Task ClearLoginUser(string account) //{ // var list = await _cache.ReadAsync>(account); // if (list != null) // { // foreach (var token in list) // { // await _cache.RemoveAsync(token); // } // await _cache.RemoveAsync(account); // } //} /// /// 生成jwt令牌 /// /// 用户id /// 用户名称 /// 用户账号 /// public string EncodeToken(string userId, string userName, string account) { var token = new JwtBuilder() .WithAlgorithm(new HMACSHA256Algorithm()) .WithSecret(ConfigHelper.GetConfig().JwtSecret) .AddClaim("iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds()) .AddClaim("exp", DateTimeOffset.UtcNow.AddHours(12).ToUnixTimeSeconds()) // 设置12小时过期 .AddClaim("UserId", userId).AddClaim("UserName", userName).AddClaim("Account", account) .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"); } } } }