protected override void OnAuthorization(AuthorizationContext filterContext) { var anonymous = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AnonymousAttribute), false); var api = filterContext.ActionDescriptor.GetCustomAttributes(typeof(ApiAttribute), false); if (anonymous.Length == 1 ) //允许匿名访问 { } else if (api.Length == 1) { PassportEngine pe = new PassportEngine(); LoginIdentity ui = pe.CreateIdentity(System.Web.HttpContext.Current); string sid = System.Web.HttpContext.Current.Request.Headers["sid"]; if (ui.UserID > 0) { ViewData["User"] = ui; } else if (!string.IsNullOrEmpty(sid)) { ViewData["User"] = new LoginIdentity(Convert.ToInt32(sid),string.Empty,sid); } else { ViewData["User"] = new LoginIdentity(); } } else { PassportEngine pe = new PassportEngine(); LoginIdentity ui = pe.CreateIdentity(System.Web.HttpContext.Current); if (ui.UserID <= 0) { filterContext.Result = new RedirectResult(ConfigurationManager.AppSettings["LoginUrl"]); } ViewData["User"] = ui; } ViewData["iPhone"] = false; if (System.Web.HttpContext.Current.Request.Headers["platform"] != null && System.Web.HttpContext.Current.Request.Headers["platform"].ToLower() == "iphone") { ViewData["iPhone"] = true; } base.OnAuthorization(filterContext); }
public LoginIdentity CreateIdentity(HttpContext context) { HttpCookie cookie = context.Request.Cookies[CookieName]; if (cookie == null) return LoginIdentity.Anonymous; else { // 刷新Cookie过期时间 if (ExpireTime > 0) { long ticks = Convert.ToInt64(cookie.Values["expiry"]); DateTime expiry = new DateTime(ticks); if (expiry <= DateTime.Now) return LoginIdentity.Anonymous; //else //{ // cookie.Values["expiry"] = DateTime.Now.AddMinutes(ExpireTime).Ticks.ToString(); // context.Response.Cookies.Add(cookie); //} else { if (isRemember) { cookie.Values["expiry"] = DateTime.Now.AddDays(ExpireTime).Ticks.ToString(); cookie.Expires = DateTime.Now.AddDays(ExpireTime); context.Response.Cookies.Add(cookie); } else { cookie.Values["expiry"] = DateTime.Now.AddMinutes(ExpireTime).Ticks.ToString(); cookie.Expires = DateTime.Now.AddHours(ExpireTime); context.Response.Cookies.Add(cookie); } } } string id = cookie.Values["id"]; string name = DecodeCookieValue(cookie.Values["name"]); bool remember = Convert.ToBoolean(cookie.Values["remember"]); if (Encrypt) { id = EncryptHelper.AESDecrypt(id); name = EncryptHelper.AESDecrypt(name); } LoginIdentity identity = new LoginIdentity(Convert.ToInt32(id), name); return identity; } }