private static bool Check(JWTPlayloadInfo playload, string cacheToken, string token) { if (string.IsNullOrEmpty(cacheToken)) { return(false); } if (string.IsNullOrEmpty(token)) { return(false); } if (!cacheToken.Equals(token)) { return(false); } //Token过期 DateTime exp = DateTimeHelper.GetDateTime(playload.exp); if (DateTime.Now > exp) { if (!string.IsNullOrEmpty(playload.aud) && playload.aud.Equals("guest")) { CacheFactory.GetCacheInstance().RemoveCache("JWT_TokenCacheKey:Guest"); } else { CacheFactory.GetCacheInstance().RemoveCache(string.Format("JWT_TokenCacheKey:{0}", playload.aud)); } return(false); } return(true); }
/// <summary> /// 数据字典列表 /// </summary> /// <returns></returns> public IEnumerable <DataItemViewModel> GetDataItemList() { //List<DataItemViewModel> cacheList = CacheFactory.GetCacheInstance().GetListCache<DataItemViewModel>(_dataItemDetailBll.CacheKey, out long total); //if (cacheList == null || cacheList.Count == 0) //{ // cacheList = _dataItemDetailBll.GetDataItemList().ToList(); // //以集合的方式存在缓存下面 // CacheFactory.GetCacheInstance().WriteListCache<DataItemViewModel>(cacheList, _dataItemDetailBll.CacheKey); // //以单体的形式存在缓存下面 // //foreach (DataItemViewModel model in cacheList) // //{ // // CacheFactory.GetCacheInstance().WriteCache<DataItemViewModel>(model, _dataItemDetailBll.CacheKey); // //} //} //return cacheList; List <DataItemViewModel> cacheList = CacheFactory.GetCacheInstance().GetListCache <DataItemViewModel>( _dataItemDetailBll.CacheKey, () => { return(_dataItemDetailBll.GetDataItemList().ToList()); }, out long total); return(cacheList); }
/// <summary> /// 获取所有modelTypes /// </summary> /// <returns></returns> private List <Type> GetAllModelTypes() { ICacheProvider dalCacheFactory = CacheFactory.GetCacheInstance(CacheProviderType.LOCALMEMORYCACHE); List <Type> modelTypes = dalCacheFactory.Get <List <Type> >("cache_modelType"); return(modelTypes); }
/// <summary> /// 是否过期 /// </summary> /// <returns></returns> public virtual bool IsOverdue() { try { string str = ""; if (_loginProvider == "Cookie") { str = CookieHelper.GetCookie(LoginUserKey); } else if (_loginProvider == "Session") { str = SessionHelper.GetSession <string>(LoginUserKey); } else if (_loginProvider == "Cache") { str = CacheFactory.GetCacheInstance().GetCache <string>(LoginUserKey); } return(string.IsNullOrEmpty(str)); } catch (Exception) { return(true); } }
/// <summary> /// 写入登录信息 /// </summary> /// <param name="user">成员信息</param> public virtual void AddCurrent(OperatorEntity user) { try { if (_loginProvider == "Cookie") { CookieHelper.WriteCookie(LoginUserKey, DESEncryptHelper.Encrypt(user.TryToJson()), 60); } else if (_loginProvider == "Session") { SessionHelper.AddSession(LoginUserKey, DESEncryptHelper.Encrypt(user.TryToJson()), 60, 0); } else if (_loginProvider == "Cache") { CacheFactory.GetCacheInstance().WriteCache(DESEncryptHelper.Encrypt(user.TryToJson()), LoginUserKey, user.LoginTime.AddMinutes(60)); } //添加当前登陆用户Token CacheFactory.GetCacheInstance().WriteCache(user.Token, user.UserId, user.LoginTime.AddMinutes(60)); } catch (Exception ex) { throw new Exception(ex.Message); } }
/// <summary> /// 如果Token过期,则马上重新计算 /// </summary> /// <param name="userId"></param> /// <param name="account"></param> public static void CheckTokenHasExpiry(string userId, string account) { if (!string.IsNullOrEmpty(userId) && userId.Equals("guest")) { bool has = CacheFactory.GetCacheInstance().HasExpire("JWT_TokenCacheKey:Guest"); if (has) { JWTPlayloadInfo playload = new JWTPlayloadInfo { iss = "S_COMMON_TOKTN", sub = account, aud = userId, userid = CommonHelper.GetGuid(), extend = "PUBLIC_TOKTN" }; GetToken(playload); } } else { bool has = CacheFactory.GetCacheInstance().HasExpire(string.Format("JWT_TokenCacheKey:{0}", userId)); if (has) { JWTPlayloadInfo playload = new JWTPlayloadInfo { iss = "S_USER_TOKTN", sub = account, aud = userId, userid = CommonHelper.GetGuid(), extend = "USER_TOKTN" }; GetToken(playload); } } }
/// <summary> /// 签发Token /// </summary> /// <param name="playload">载荷</param> /// <returns></returns> public static string GetToken(JWTPlayloadInfo playload) { string token = String.Empty; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); //设置过期时间 DateTime time = DateTime.Now.AddMinutes(120); playload.exp = DateTimeHelper.GetTimeStamp(time).ToString(); Dictionary <string, object> dict = playload.Object2Dictionary(); //获取私钥 string secret = GetSecret(); //将Token保存在缓存中 if (!string.IsNullOrEmpty(playload.aud) && playload.aud.Equals("guest")) { //计算公用Token token = CacheFactory.GetCacheInstance().GetCache("JWT_TokenCacheKey:Guest", () => { return(encoder.Encode(dict, secret)); }, time); } else { //计算Token token = CacheFactory.GetCacheInstance().GetCache(string.Format("JWT_TokenCacheKey:{0}", playload.aud), () => { return(encoder.Encode(dict, secret)); }, time); } return(token); }
private void RedisTest() { RedisHelper redis = new RedisHelper(); List <string> keys = redis.GetKeys(); Console.WriteLine("__TestBaseEntityKey是否存储:" + redis.KeyExists("__TestBaseEntityKey") + "\r\n"); keys.ForEach(k => { bool e = redis.KeyExists(k); Console.WriteLine(k + "是否存储:" + e + "\r\n"); }); Console.WriteLine("==========================="); DataItemCache dataItem = new DataItemCache(); var res = dataItem.GetDataItemList(); Console.WriteLine("res:" + res.Count()); Console.WriteLine("==========================="); BaseEntity cache = CacheFactory.GetCacheInstance().GetCache <BaseEntity>("__TestBaseEntityKey"); if (cache == null) { cache = new BaseEntity { Id = "123", PK = 1 }; CacheFactory.GetCacheInstance().WriteCache <BaseEntity>(cache, "__TestBaseEntityKey"); } Console.WriteLine(cache.Id); }
/// <summary> /// 刷新缓存 /// </summary> /// <returns></returns> public void RefreshCache(DateTime expireTime) { bool hasExpire = CacheFactory.GetCacheInstance().HasExpire(busines.CacheKey); if (!hasExpire) { var cacheList = busines.GetUserGroupList().ToList(); CacheFactory.GetCacheInstance().WriteListCache<RoleEntity>(cacheList, busines.CacheKey, expireTime); } }
/// <summary> /// 用户组列表 /// </summary> /// <returns></returns> public IEnumerable<RoleEntity> GetList() { var cacheList = CacheFactory.GetCacheInstance().GetListCache<RoleEntity>(busines.CacheKey, out long toatl); if (cacheList == null || cacheList.Count == 0) { cacheList = busines.GetUserGroupList().ToList(); CacheFactory.GetCacheInstance().WriteListCache<RoleEntity>(cacheList, busines.CacheKey); } return cacheList; }
/// <summary> /// 移除用户扩展缓存 /// </summary> /// <param name="username">用户名</param> public static void RemoveExtendCache(string username) { if (!string.IsNullOrEmpty(username)) { ICacheProvider cacheFactory = CacheFactory.GetCacheInstance(CacheProviderType.LOCALMEMORYCACHE); if (cacheFactory != null) { cacheFactory.Remove(username); } } }
/// <summary> /// 缓存用户扩展信息 /// </summary> /// <param name="username">用户名</param> /// <param name="extend">用户扩展信息</param> public static void CacheUserExtendInfo(string username, UserExtendBase extend) { if (!string.IsNullOrEmpty(username) && extend != null) { ICacheProvider cacheFactory = CacheFactory.GetCacheInstance(CacheProviderType.LOCALMEMORYCACHE); if (cacheFactory != null) { cacheFactory.Set(username, extend); } } }
/// <summary> /// 部门列表 /// </summary> /// <returns></returns> public IEnumerable <DepartmentEntity> GetList() { List <DepartmentEntity> cacheList = CacheFactory.GetCacheInstance().GetListCache <DepartmentEntity>(busines.CacheKey, out long total); if (cacheList == null || cacheList.Count == 0) { cacheList = busines.GetDepartmentList().ToList(); CacheFactory.GetCacheInstance().WriteListCache <DepartmentEntity>(cacheList, busines.CacheKey); } return(cacheList); }
/// <summary> /// 获取用户扩展信息 /// </summary> /// <param name="username">用户名</param> /// <returns></returns> public static UserExtendBase GetUserExtendCache(string username) { if (!string.IsNullOrEmpty(username)) { ICacheProvider cacheFactory = CacheFactory.GetCacheInstance(CacheProviderType.LOCALMEMORYCACHE); if (cacheFactory != null) { return(cacheFactory.Get <UserExtendBase>(username)); } } return(null); }
/// <summary> /// 根据编码获取项目 /// </summary> /// <param name="code"></param> /// <returns></returns> public DataItemEntity GetDataItemEntityByCode(string code) { if (!string.IsNullOrEmpty(code)) { DataItemEntity entity = CacheFactory.GetCacheInstance().GetCache <DataItemEntity>("__" + code); if (entity == null) { entity = _dataItemBll.GetEntityByCode(code); CacheFactory.GetCacheInstance().WriteCache(entity, "__" + code); } return(entity); } return(default(DataItemEntity)); }
/// <summary> /// 保存区域表单(新增、修改) /// </summary> /// <param name="keyValue">主键值</param> /// <param name="areaEntity">区域实体</param> /// <returns></returns> public void SaveForm(string keyValue, AreaEntity areaEntity) { if (!string.IsNullOrEmpty(keyValue)) { areaEntity.Modify(keyValue); this.BaseRepository().Update(areaEntity); } else { areaEntity.Create(); this.BaseRepository().Insert(areaEntity); } CacheFactory.GetCacheInstance().RemoveCache("__AreaCache"); }
/// <summary> /// 删除登录信息 /// </summary> public virtual void EmptyCurrent() { if (_loginProvider == "Cookie") { CookieHelper.DelCookie(LoginUserKey); } else if (_loginProvider == "Session") { SessionHelper.RemoveSession(LoginUserKey.Trim()); } else if (_loginProvider == "Cache") { CacheFactory.GetCacheInstance().RemoveCache(LoginUserKey); } }
/// <summary> /// 刷新缓存 /// </summary> /// <returns></returns> public void RefreshCache(DateTime expireTime) { bool hasExpire = CacheFactory.GetCacheInstance().HasExpire(_dataItemDetailBll.CacheKey); if (!hasExpire) { var cacheList = _dataItemDetailBll.GetDataItemList().ToList(); //以集合的方式存在缓存下面 CacheFactory.GetCacheInstance().WriteListCache <DataItemViewModel>(cacheList, _dataItemDetailBll.CacheKey, expireTime); //以单体的形式存在缓存下面 //foreach (DataItemViewModel model in cacheList) //{ // CacheFactory.GetCacheInstance().WriteCache<DataItemViewModel>(model, _dataItemDetailBll.CacheKey); //} } }
/// <summary> /// 刷新缓存 /// </summary> /// <returns></returns> public void RefreshCache(DateTime expireTime) { bool hasExpire = CacheFactory.GetCacheInstance().HasExpire(areaBll.CacheKey); if (!hasExpire) { var cacheList = areaBll.GetList().ToList(); //以集合的方式存在缓存下面 //CacheFactory.GetCacheInstance().WriteListCache<AreaEntity>(cacheList, areaBll.CacheKey); //以单体的形式存在缓存下面 foreach (AreaEntity model in cacheList) { CacheFactory.GetCacheInstance().WriteCache <AreaEntity>(model, areaBll.CacheKey, expireTime); } } }
/// <summary> /// 区域列表 /// </summary> /// <returns></returns> private IEnumerable <AreaEntity> GetList() { var cacheList = CacheFactory.GetCacheInstance().GetListCache <AreaEntity>(areaBll.CacheKey, out long total); if (cacheList == null || cacheList.Count == 0) { cacheList = areaBll.GetList().ToList(); //以集合的方式存在缓存下面 //CacheFactory.GetCacheInstance().WriteListCache<AreaEntity>(cacheList, areaBll.CacheKey); //以单体的形式存在缓存下面 foreach (AreaEntity model in cacheList) { CacheFactory.GetCacheInstance().WriteCache <AreaEntity>(model, areaBll.CacheKey); } } return(cacheList); }
/// <summary> /// Token校验 /// </summary> /// <param name="token"></param> /// <returns></returns> public static JWTPlayloadInfo CheckToken(string token) { if (string.IsNullOrEmpty(token)) { return(null); } IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder); //获取私钥 string secret = GetSecret(); try { JWTPlayloadInfo playload = decoder.DecodeToObject <JWTPlayloadInfo>(token, secret, true); if (playload != null) { if (!string.IsNullOrEmpty(playload.aud) && playload.aud.Equals("guest")) { string cacheToken = CacheFactory.GetCacheInstance().GetCache <string>("JWT_TokenCacheKey:Guest"); return(Check(playload, cacheToken, token) ? playload : null); } else { string cacheToken = CacheFactory.GetCacheInstance().GetCache <string>(string.Format("JWT_TokenCacheKey:{0}", playload.aud)); return(Check(playload, cacheToken, token) ? playload : null); } } } catch (Exception e) { return(null); } return(null); }
/// <summary> /// 当前用户 /// </summary> /// <returns></returns> public virtual OperatorEntity Current() { try { OperatorEntity user = new OperatorEntity(); if (_loginProvider == "Cookie") { string json = CookieHelper.GetCookie(LoginUserKey).ToString(); if (!string.IsNullOrEmpty(json)) { user = DESEncryptHelper.Decrypt(json).JsonToEntity <OperatorEntity>(); } } else if (_loginProvider == "Session") { string json = SessionHelper.GetSession <string>(LoginUserKey).ToString(); if (!string.IsNullOrEmpty(json)) { user = DESEncryptHelper.Decrypt(json).JsonToEntity <OperatorEntity>(); } } else if (_loginProvider == "Cache") { string json = CacheFactory.GetCacheInstance().GetCache <string>(LoginUserKey); if (!string.IsNullOrEmpty(json)) { user = DESEncryptHelper.Decrypt(json).JsonToEntity <OperatorEntity>(); } } return(user); } catch (Exception ex) { throw new Exception(ex.Message); } }
/// <summary> /// 是否已登录 /// </summary> /// <returns></returns> public virtual int IsOnLine() { OperatorEntity user = new OperatorEntity(); if (_loginProvider == "Cookie") { user = DESEncryptHelper.Decrypt(CookieHelper.GetCookie(LoginUserKey).ToString()).JsonToEntity <OperatorEntity>(); } else if (_loginProvider == "Session") { user = DESEncryptHelper.Decrypt(SessionHelper.GetSession <string>(LoginUserKey).ToString()).JsonToEntity <OperatorEntity>(); } else if (_loginProvider == "Cache") { string json = CacheFactory.GetCacheInstance().GetCache <string>(LoginUserKey); if (!string.IsNullOrEmpty(json)) { user = DESEncryptHelper.Decrypt(json).JsonToEntity <OperatorEntity>(); } } string token = CacheFactory.GetCacheInstance().GetCache <string>(user.UserId); if (string.IsNullOrEmpty(token)) { return(-1);//过期 } if (user.Token == token.ToString()) { return(1);//正常 } else { return(0);//已登录 } }
/// <summary> /// Action执行权限认证 /// </summary> /// <param name="userId">用户Id</param> /// <param name="moduleId">模块Id</param> /// <param name="action">请求地址</param> /// <returns></returns> public bool ActionAuthorize(string userId, string moduleId, string action) { List <AuthorizeUrlModel> authorizeUrlList = CacheFactory.GetCacheInstance().GetCache <List <AuthorizeUrlModel> >("__ActionAuthorize_" + userId); if (authorizeUrlList == null || authorizeUrlList.Count == 0) { authorizeUrlList = this.GetUrlList(userId).ToList(); CacheFactory.GetCacheInstance().WriteCache(authorizeUrlList, "__ActionAuthorize_" + userId, DateTime.Now.AddMinutes(30)); } authorizeUrlList = authorizeUrlList.FindAll(a => a.ModuleId == moduleId); foreach (AuthorizeUrlModel item in authorizeUrlList) { if (!string.IsNullOrEmpty(item.UrlAddress)) { string[] url = item.UrlAddress.Split('?'); if (item.ModuleId == moduleId && url[0] == action) { return(true); } } } return(false); }
/// <summary> /// 删除区域 /// </summary> /// <param name="keyValue">主键</param> public void RemoveForm(string keyValue) { CacheFactory.GetCacheInstance().RemoveCache("__AreaCache"); this.BaseRepository().Delete(keyValue); }
/// <summary> /// 正在请求时 /// </summary> /// <param name="actionContext"></param> public override void OnActionExecuting(HttpActionContext actionContext) { string isInterfaceSignature = ConfigHelper.GetValue("IsInterfaceSignature"); if (isInterfaceSignature.ToLower() == "false") { base.OnActionExecuting(actionContext); return; } BaseJsonResult <string> resultMsg = null; //操作上下文请求信息 HttpRequestMessage request = actionContext.Request; //请求方法 //string method = request.Method.Method; string appkey = string.Empty, timestamp = string.Empty, nonce = string.Empty, access_token = string.Empty; //string authority = request.RequestUri.Authority; //string host = request.RequestUri.Host; //string port = request.RequestUri.Port.ToString(); //if (request.IsLocal()) //{ //} //参数列表 //Dictionary<string, object> dictionary = actionContext.ActionArguments; //if (dictionary.ContainsKey("arg")) //{ //} //用户编号 if (request.Headers.Contains("AppKey")) { appkey = HttpUtility.UrlDecode(request.Headers.GetValues("AppKey").FirstOrDefault()); } //时间戳 if (request.Headers.Contains("TimeStamp")) { timestamp = HttpUtility.UrlDecode(request.Headers.GetValues("TimeStamp").FirstOrDefault()); } //随机数 if (request.Headers.Contains("Nonce")) { nonce = HttpUtility.UrlDecode(request.Headers.GetValues("Nonce").FirstOrDefault()); } //数字签名数据 if (request.Headers.Contains("Authorization")) { access_token = HttpUtility.UrlDecode(request.Headers.GetValues("Authorization").FirstOrDefault()); } //接受客户端预请求 if (actionContext.Request.Method == HttpMethod.Options) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Accepted); base.OnActionExecuting(actionContext); return; } //GetToken和Login方法不需要进行签名验证 string[] exceptRequest = GlobalConstCode.NOT_NEED_DIGITAL_SIGNATURE; if (exceptRequest.Contains(actionContext.ActionDescriptor.ActionName)) { if (string.IsNullOrEmpty(appkey) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(nonce)) { resultMsg = new BaseJsonResult <string> { Status = (int)JsonObjectStatus.ParameterError, Message = JsonObjectStatus.ParameterError.GetEnumDescription(), Data = "" }; actionContext.Response = resultMsg.TryToHttpResponseMessage(); base.OnActionExecuting(actionContext); return; } else { base.OnActionExecuting(actionContext); return; } //base.OnActionExecuting(actionContext); //return; } //判断请求头是否包含以下参数 if (string.IsNullOrEmpty(appkey) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(nonce) || string.IsNullOrEmpty(access_token)) //if (string.IsNullOrEmpty(access_token) || string.IsNullOrEmpty(appkey)) { resultMsg = new BaseJsonResult <string> { Status = (int)JsonObjectStatus.ParameterError, Message = JsonObjectStatus.ParameterError.GetEnumDescription(), Data = "" }; actionContext.Response = resultMsg.TryToHttpResponseMessage(); base.OnActionExecuting(actionContext); return; } //判断当前时间戳是否有效 long now = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000; //客户端传入得时间戳 long qeruest = 0; bool timespanvalidate = long.TryParse(timestamp, out qeruest); //当前时间必与请求时间差应在1分钟以内才算有效时间戳,防止伪造时间戳 bool falg = (now - qeruest) < 1 * 60; //如果时间差大于1分钟或者时间戳转换失败则视为无效时间戳 if (!falg || !timespanvalidate) { resultMsg = new BaseJsonResult <string> { Status = (int)JsonObjectStatus.UrlExpireError, Message = JsonObjectStatus.UrlExpireError.GetEnumDescription(), Data = "" }; actionContext.Response = resultMsg.TryToHttpResponseMessage(); base.OnActionExecuting(actionContext); return; } //判断token是否有效 TokenViewModel token = CacheFactory.GetCacheInstance().GetCache <TokenViewModel>(appkey); string serveraccesstoken = "AccessToken "; if (token == null) { resultMsg = new BaseJsonResult <string> { Status = (int)JsonObjectStatus.TokenInvalid, Message = JsonObjectStatus.TokenInvalid.GetEnumDescription(), Data = "" }; actionContext.Response = resultMsg.TryToHttpResponseMessage(); base.OnActionExecuting(actionContext); return; } else { serveraccesstoken += token.AccessToken; } #region 请求参数签名,GET请求即参数不带?、&、=符号,如id1nametest;POST请求将数据序列化成Json字符串 //请求参数签名,GET请求即参数不带?、&、=符号,如id1nametest;POST请求将数据序列化成Json字符串 //string data; //switch (method)//根据请求类型拼接参数 //{ // case "POST": // Stream stream = HttpContext.Current.Request.InputStream; // StreamReader streamReader = new StreamReader(stream); // data = streamReader.ReadToEnd(); // break; // case "GET": // NameValueCollection form = HttpContext.Current.Request.QueryString; // //第一步:取出所有get参数 // IDictionary<string, string> parameters = new Dictionary<string, string>(); // for (int f = 0; f < form.Count; f++) // { // string key = form.Keys[f]; // parameters.Add(key, form[key]); // } // // 第二步:把字典按Key的字母顺序排序 // IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters); // // ReSharper disable once GenericEnumeratorNotDisposed // IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator(); // // 第三步:把所有参数名和参数值串在一起 // StringBuilder query = new StringBuilder(); // while (dem.MoveNext()) // { // string key = dem.Current.Key; // string value = dem.Current.Value; // if (!string.IsNullOrEmpty(key)) // { // query.Append(key).Append(value); // } // } // data = query.ToString(); // break; // default: // resultMsg = new BaseJson<string> // { // Status = (int)JsonObjectStatus.HttpMehtodError, // Message = JsonObjectStatus.HttpMehtodError.GetEnumDescription(), // Data = "" // }; // actionContext.Response = resultMsg.ToJson().ToHttpResponseMessage(); // base.OnActionExecuting(actionContext); // return; //} #endregion //校验签名信息 bool result = SignExtension.ValidateSign(appkey, nonce, timestamp, serveraccesstoken, access_token); if (!result) { resultMsg = new BaseJsonResult <string> { Status = (int)JsonObjectStatus.HttpRequestError, Message = JsonObjectStatus.HttpRequestError.GetEnumDescription(), Data = "" }; actionContext.Response = resultMsg.TryToHttpResponseMessage(); base.OnActionExecuting(actionContext); } else { base.OnActionExecuting(actionContext); } }