From 1a1ec43c57d71358fe54c13010b5d5d1264029c7 Mon Sep 17 00:00:00 2001 From: yubaolee Date: Thu, 17 Nov 2016 19:48:12 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96sso?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Infrastructure/Cache/CacheObj.cs | 16 ++++ .../Cache/CacheProvider.cs | 17 ++-- Infrastructure/Cache/EnyimMemcachedContext.cs | 4 +- ...onContext.cs => HttpApplicationContext.cs} | 20 ++-- Infrastructure/Cache/ICache.cs | 48 ---------- .../{CacheContext.cs => ICacheContext.cs} | 6 +- Infrastructure/Cache/ObjCacheProvider.cs | 65 +++++++++++++ Infrastructure/Cache/RuntimeMemoryCache.cs | 93 ------------------- Infrastructure/Infrastructure.csproj | 9 +- OpenAuth.App/OpenAuth.App.csproj | 1 - OpenAuth.App/SSO/AppInfoService.cs | 3 +- OpenAuth.App/SSO/SSOAuthAttribute.cs | 40 ++++---- OpenAuth.App/SSO/SSOController.cs | 25 +---- OpenAuth.App/SSO/UserAuthSessionService.cs | 11 ++- 14 files changed, 141 insertions(+), 217 deletions(-) create mode 100644 Infrastructure/Cache/CacheObj.cs rename OpenAuth.App/SSO/ServiceContext.cs => Infrastructure/Cache/CacheProvider.cs (78%) rename Infrastructure/Cache/{SessionContext.cs => HttpApplicationContext.cs} (71%) delete mode 100644 Infrastructure/Cache/ICache.cs rename Infrastructure/Cache/{CacheContext.cs => ICacheContext.cs} (89%) create mode 100644 Infrastructure/Cache/ObjCacheProvider.cs delete mode 100644 Infrastructure/Cache/RuntimeMemoryCache.cs diff --git a/Infrastructure/Cache/CacheObj.cs b/Infrastructure/Cache/CacheObj.cs new file mode 100644 index 00000000..d1d59ac3 --- /dev/null +++ b/Infrastructure/Cache/CacheObj.cs @@ -0,0 +1,16 @@ +using System; + +namespace Helper.Cache +{ + [Serializable] + public class CacheObj + { + public string key { get; set; } + + public T Obj { get; set; } + + public DateTime InvalidTime { get; set; } + + public DateTime CreateTime { get; set; } + } +} \ No newline at end of file diff --git a/OpenAuth.App/SSO/ServiceContext.cs b/Infrastructure/Cache/CacheProvider.cs similarity index 78% rename from OpenAuth.App/SSO/ServiceContext.cs rename to Infrastructure/Cache/CacheProvider.cs index 5861ba9c..667eff5d 100644 --- a/OpenAuth.App/SSO/ServiceContext.cs +++ b/Infrastructure/Cache/CacheProvider.cs @@ -1,21 +1,24 @@ using System; using System.Globalization; -using Infrastructure.Cache; -namespace OpenAuth.App.SSO +namespace Helper.Cache { - public abstract class ServiceContext : IDisposable + /// + /// 缓存工厂 + /// 李玉宝新增于2016-11-09 9:42:52 + /// + public abstract class CacheProvider : IDisposable { /// /// 缓存组件 /// - public CacheContext CacheContext { get; private set; } + public ICacheContext CacheContext { get; private set; } /// /// 动态设置缓存对象的新实例 /// /// 缓存实例对象 - public void SetCacheInstance(CacheContext cacheContext) + public void SetCacheInstance(ICacheContext cacheContext) { //先释放现有的缓存组件 if (CacheContext != null) @@ -34,7 +37,7 @@ namespace OpenAuth.App.SSO throw new ArgumentNullException("cacheContextType"); } - if (!typeof(CacheContext).IsAssignableFrom(cacheContextType)) + if (!typeof(ICacheContext).IsAssignableFrom(cacheContextType)) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, "该类型 {0} 必须继承自抽象类CacheContext", cacheContextType), @@ -43,7 +46,7 @@ namespace OpenAuth.App.SSO try { - CacheContext = Activator.CreateInstance(cacheContextType) as CacheContext; + CacheContext = Activator.CreateInstance(cacheContextType) as ICacheContext; } catch (Exception ex) { diff --git a/Infrastructure/Cache/EnyimMemcachedContext.cs b/Infrastructure/Cache/EnyimMemcachedContext.cs index 4944b4f5..24e407b7 100644 --- a/Infrastructure/Cache/EnyimMemcachedContext.cs +++ b/Infrastructure/Cache/EnyimMemcachedContext.cs @@ -13,9 +13,9 @@ using Enyim.Caching; using Enyim.Caching.Memcached; -namespace Infrastructure.Cache +namespace Helper.Cache { - public sealed class EnyimMemcachedContext : CacheContext + public sealed class EnyimMemcachedContext : ICacheContext { private readonly MemcachedClient _memcachedClient = new MemcachedClient("memcached"); diff --git a/Infrastructure/Cache/SessionContext.cs b/Infrastructure/Cache/HttpApplicationContext.cs similarity index 71% rename from Infrastructure/Cache/SessionContext.cs rename to Infrastructure/Cache/HttpApplicationContext.cs index 4b774f53..3913cf5b 100644 --- a/Infrastructure/Cache/SessionContext.cs +++ b/Infrastructure/Cache/HttpApplicationContext.cs @@ -1,21 +1,25 @@ // *********************************************************************** -// Assembly : Infrastructure -// Author : yubaolee -// Created : 06-21-2016 +// Assembly : Helper +// Author : Administrator +// Created : 09-21-2016 // -// Last Modified By : yubaolee -// Last Modified On : 06-21-2016 +// Last Modified By : Administrator +// Last Modified On : 11-09-2016 // Contact : -// File: EnyimMemcachedContext.cs +// File: HttpApplicationContext.cs // *********************************************************************** using System; using System.Web; -namespace Infrastructure.Cache +namespace Helper.Cache { - public sealed class SessionContext : CacheContext + /// + /// 基于HttpApplication的存储 + /// 李玉宝新增于2016-11-09 9:30:51 + /// + public sealed class HttpApplicationContext : ICacheContext { public override void Init() diff --git a/Infrastructure/Cache/ICache.cs b/Infrastructure/Cache/ICache.cs deleted file mode 100644 index 7ade6edb..00000000 --- a/Infrastructure/Cache/ICache.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Infrastructure.Cache -{ - public interface ICache - { - /// - /// 加入缓存项 - /// - /// 缓存项标识 - /// 缓存项 - /// 缓存失效时间 - void Add(string key, object value, TimeSpan timeSpan); - /// - /// 加入依赖物理文件的缓存项 - /// - /// 缓存项标识 - /// 缓存项 - /// 依赖的文件全路径 - void AddWithFileDependency(string key, object value, string fullFileNameOfFileDependency); - /// - /// 获取缓存项 - /// - /// - /// - object Get(string cacheKey); - T Get(string cacheKey) where T : class; - void Remove(string cacheKey); - /// - /// 如果不存在缓存项则添加,否则更新(相对过期) - /// - /// 缓存项标识 - /// 缓存项 - /// 缓存失效时间 - void Set(string key, object value, TimeSpan timeSpan); - /// - /// 设置绝对过期时间 - /// - /// 缓存项标识 - /// 缓存项 - /// 缓存失效时间 - void SetAbsoluteExpiration(string key, object value, TimeSpan timeSpan); - } -} diff --git a/Infrastructure/Cache/CacheContext.cs b/Infrastructure/Cache/ICacheContext.cs similarity index 89% rename from Infrastructure/Cache/CacheContext.cs rename to Infrastructure/Cache/ICacheContext.cs index 3d0e66e4..a087c618 100644 --- a/Infrastructure/Cache/CacheContext.cs +++ b/Infrastructure/Cache/ICacheContext.cs @@ -1,11 +1,11 @@ using System; -namespace Infrastructure.Cache +namespace Helper.Cache { /// - /// 策略模式缓存组件,可实现动态插拔 + /// 缓存接口 /// - public abstract class CacheContext : IDisposable + public abstract class ICacheContext : IDisposable { /// /// 初始化缓存组件 diff --git a/Infrastructure/Cache/ObjCacheProvider.cs b/Infrastructure/Cache/ObjCacheProvider.cs new file mode 100644 index 00000000..84c52d1c --- /dev/null +++ b/Infrastructure/Cache/ObjCacheProvider.cs @@ -0,0 +1,65 @@ +// *********************************************************************** +// Assembly : OpenAuth.WebApi +// Author : yubaolee +// Created : 07-11-2016 +// +// Last Modified By : yubaolee +// Last Modified On : 07-11-2016 +// Contact : +// File: CacheObjService.cs +// *********************************************************************** + +using System; + +namespace Helper.Cache +{ + /// + /// 带超时结构的缓存 + /// + public class ObjCacheProvider : CacheProvider + { + public ObjCacheProvider() + { + SetCacheInstance(new HttpApplicationContext()); + } + + public bool Create(string key, T val) + { + var cacheobj = new CacheObj + { + key = key, + InvalidTime = DateTime.Now.AddMinutes(5), + CreateTime = DateTime.Now, + Obj = val + }; + //设置缓存 + return CacheContext.Set(key, cacheobj); + } + + /// + /// 根据失效时间获取缓存 + /// 李玉宝于2016-11-08 16:54:04 + /// + /// The key. + public T GetCache(string key) + { + var cache = CacheContext.Get>(key); + if (cache == null) return default(T); + + if (cache.InvalidTime > DateTime.Now) + { + return cache.Obj; + } + + //移除无效Session缓存 + Remove(key); + + return default(T); + } + + public void Remove(string key) + { + CacheContext.Remove(key); + } + } +} \ No newline at end of file diff --git a/Infrastructure/Cache/RuntimeMemoryCache.cs b/Infrastructure/Cache/RuntimeMemoryCache.cs deleted file mode 100644 index e067c237..00000000 --- a/Infrastructure/Cache/RuntimeMemoryCache.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.Caching; -namespace Infrastructure.Cache -{ - public class RuntimeMemoryCache : ICache - { - private readonly MemoryCache memoryCache = MemoryCache.Default; - /// - /// 加入缓存项(绝对过期时间) - /// - /// 缓存项标识 - /// 缓存项 - /// 缓存失效时间 - public void Add(string key, object value, TimeSpan timeSpan) - { - if (!string.IsNullOrEmpty(key) && (value != null)) - { - CacheItemPolicy cip = new CacheItemPolicy() - { - AbsoluteExpiration = DateTime.Now.Add(timeSpan) - }; - this.memoryCache.Add(key, value, cip, null); - } - } - /// - /// 加入依赖物理文件的缓存项 - /// - /// 缓存项标识 - /// 缓存项 - /// 依赖的文件全路径 - public void AddWithFileDependency(string key, object value, string fullFileNameOfFileDependency) - { - if (!string.IsNullOrEmpty(key) && (value != null)) - { - CacheItemPolicy policy = new CacheItemPolicy - { - AbsoluteExpiration = DateTimeOffset.Now.AddMonths(1) - }; - policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List { fullFileNameOfFileDependency })); - this.memoryCache.Add(key, value, policy, null); - } - } - - public object Get(string cacheKey) - { - return this.memoryCache[cacheKey]; - } - - public T Get(string cacheKey) where T : class - { - object obj = this.Get(cacheKey); - if (obj != null) - { - return (obj as T); - } - return default(T); - } - - public void Remove(string cacheKey) - { - this.memoryCache.Remove(cacheKey, null); - } - /// - /// 如果不存在缓存项则添加,否则更新(相对过期) - /// - /// 缓存项标识 - /// 缓存项 - /// 缓存失效时间 - public void Set(string key, object value, TimeSpan timeSpan) - { - CacheItemPolicy cip = new CacheItemPolicy() - { - SlidingExpiration = timeSpan, - }; - this.memoryCache.Set(key, value, cip, null); - } - /// - /// 设置绝对过期时间 - /// - /// 缓存项标识 - /// 缓存项 - /// 缓存失效时间 - public void SetAbsoluteExpiration(string key, object value, TimeSpan timeSpan) - { - CacheItemPolicy cip = new CacheItemPolicy() - { - AbsoluteExpiration = DateTime.Now.Add(timeSpan), - }; - this.memoryCache.Set(key, value, cip, null); - } - } -} diff --git a/Infrastructure/Infrastructure.csproj b/Infrastructure/Infrastructure.csproj index 5c0345dd..e63e35da 100644 --- a/Infrastructure/Infrastructure.csproj +++ b/Infrastructure/Infrastructure.csproj @@ -80,11 +80,12 @@ - + + - - - + + + diff --git a/OpenAuth.App/OpenAuth.App.csproj b/OpenAuth.App/OpenAuth.App.csproj index b3133b17..de7f4437 100644 --- a/OpenAuth.App/OpenAuth.App.csproj +++ b/OpenAuth.App/OpenAuth.App.csproj @@ -93,7 +93,6 @@ - diff --git a/OpenAuth.App/SSO/AppInfoService.cs b/OpenAuth.App/SSO/AppInfoService.cs index 794c62b8..90974a08 100644 --- a/OpenAuth.App/SSO/AppInfoService.cs +++ b/OpenAuth.App/SSO/AppInfoService.cs @@ -1,9 +1,10 @@ using System; using System.Linq; +using Helper.Cache; namespace OpenAuth.App.SSO { - public class AppInfoService : ServiceContext + public class AppInfoService : CacheProvider { public AppInfo Get(string appKey) { diff --git a/OpenAuth.App/SSO/SSOAuthAttribute.cs b/OpenAuth.App/SSO/SSOAuthAttribute.cs index 83ca006c..3c019a06 100644 --- a/OpenAuth.App/SSO/SSOAuthAttribute.cs +++ b/OpenAuth.App/SSO/SSOAuthAttribute.cs @@ -1,45 +1,42 @@ -using System.Web; +using System; +using System.Web; using System.Web.Mvc; namespace OpenAuth.App.SSO { + /// + /// 采用Attribute的方式验证登陆 + /// 李玉宝新增于2016-11-09 10:08:10 + /// public class SSOAuthAttribute : ActionFilterAttribute { public const string Token = "Token"; - public const string SessionUserName = "SessionUserName"; public override void OnActionExecuting(ActionExecutingContext filterContext) { var token = ""; - var cookieSessionUserName = ""; //Token by QueryString var request = filterContext.HttpContext.Request; if (request.QueryString[Token] != null) { token = request.QueryString[Token]; - filterContext.HttpContext.Response.Cookies.Add(new HttpCookie(Token, token)); + var cookie = new HttpCookie(Token, token) + { + Expires = DateTime.Now.AddDays(1) + }; + filterContext.HttpContext.Response.Cookies.Add(cookie); } else if (request.Cookies[Token] != null) //从Cookie读取Token { token = request.Cookies[Token].Value; } - //SessionUserName by QueryString - if (request.QueryString[SessionUserName] != null) - { - cookieSessionUserName = request.QueryString[SessionUserName]; - filterContext.HttpContext.Response.Cookies.Add(new HttpCookie(SessionUserName, cookieSessionUserName)); - } - else if (request.Cookies[SessionUserName] != null) //从Cookie读取SessionUserName - { - cookieSessionUserName = request.Cookies[SessionUserName].Value; - } - if (string.IsNullOrEmpty(token)) { //直接登录 - filterContext.Result = LoginResult(cookieSessionUserName); + filterContext.Result = LoginResult(""); + return; } else { @@ -47,21 +44,16 @@ namespace OpenAuth.App.SSO if (AuthUtil.CheckLogin(token, request.RawUrl) == false) { //会话丢失,跳转到登录页面 - filterContext.Result = LoginResult(cookieSessionUserName); + filterContext.Result = LoginResult(""); + return; } } base.OnActionExecuting(filterContext); } - private static ActionResult LoginResult(string username) + public virtual ActionResult LoginResult(string username) { - //跳转到SSO站点登陆 - //return new RedirectResult(string.Format("{0}/sso/login?appkey={1}&username={2}", - // ConfigurationManager.AppSettings["SSOPassport"], - // ConfigurationManager.AppSettings["SSOAppKey"], - // username)); - return new RedirectResult("/Login/Index"); } } diff --git a/OpenAuth.App/SSO/SSOController.cs b/OpenAuth.App/SSO/SSOController.cs index bec7c68a..376d0007 100644 --- a/OpenAuth.App/SSO/SSOController.cs +++ b/OpenAuth.App/SSO/SSOController.cs @@ -25,12 +25,10 @@ namespace OpenAuth.App.SSO public class SSOController : Controller { public const string Token = "Token"; - public const string SessionUserName = "SessionUserName"; protected override void OnActionExecuting(ActionExecutingContext filterContext) { var token = ""; - var cookieSessionUserName = ""; //Token by QueryString var request = filterContext.HttpContext.Request; @@ -48,21 +46,10 @@ namespace OpenAuth.App.SSO token = request.Cookies[Token].Value; } - //SessionUserName by QueryString - if (request.QueryString[SessionUserName] != null) - { - cookieSessionUserName = request.QueryString[SessionUserName]; - filterContext.HttpContext.Response.Cookies.Add(new HttpCookie(SessionUserName, cookieSessionUserName)); - } - else if (request.Cookies[SessionUserName] != null) //从Cookie读取SessionUserName - { - cookieSessionUserName = request.Cookies[SessionUserName].Value; - } - if (string.IsNullOrEmpty(token)) { //直接登录 - filterContext.Result = LoginResult(cookieSessionUserName); + filterContext.Result = LoginResult(""); return; } else @@ -71,7 +58,7 @@ namespace OpenAuth.App.SSO if (AuthUtil.CheckLogin(token, request.RawUrl) == false) { //会话丢失,跳转到登录页面 - filterContext.Result = LoginResult(cookieSessionUserName); + filterContext.Result = LoginResult(""); return; } } @@ -79,14 +66,8 @@ namespace OpenAuth.App.SSO base.OnActionExecuting(filterContext); } - private static ActionResult LoginResult(string username) + public virtual ActionResult LoginResult(string username) { - //跳转到SSO站点登陆 - //return new RedirectResult(string.Format("{0}/sso/login?appkey={1}&username={2}", - // ConfigurationManager.AppSettings["SSOPassport"], - // ConfigurationManager.AppSettings["SSOAppKey"], - // username)); - return new RedirectResult("/Login/Index"); } } diff --git a/OpenAuth.App/SSO/UserAuthSessionService.cs b/OpenAuth.App/SSO/UserAuthSessionService.cs index 37d77014..650246d5 100644 --- a/OpenAuth.App/SSO/UserAuthSessionService.cs +++ b/OpenAuth.App/SSO/UserAuthSessionService.cs @@ -10,7 +10,8 @@ // *********************************************************************** using System; -using Infrastructure.Cache; +using Helper.Cache; +using Infrastructure; namespace OpenAuth.App.SSO { @@ -19,11 +20,11 @@ namespace OpenAuth.App.SSO /// 测试环境用的是基于http application的SessionContext /// 正式环境可以使用基于memcached的EnyimMemcachedContext /// - public class UserAuthSessionService : ServiceContext + public class UserAuthSessionService : CacheProvider { public UserAuthSessionService() { - SetCacheInstance(new SessionContext()); + SetCacheInstance(new HttpApplicationContext()); } public bool Create(UserAuthSession model) @@ -42,7 +43,9 @@ namespace OpenAuth.App.SSO { var cache = Get(token); if (cache == null) return false; - + LogHelper.Log(token + + "用户:" + cache.UserName + + "登陆有效时间:" + cache.InvalidTime); if (cache.InvalidTime > DateTime.Now) { //延长