private void Context_AuthenticateRequest(object sender, EventArgs e) { HttpApplication app = (HttpApplication)sender; try { if (app.Context.User != null && app.Context.User.Identity.IsAuthenticated) { if (string.IsNullOrEmpty(app.Context.User.Identity.Name)) { return; } FormsIdentity id = (FormsIdentity)app.Context.User.Identity; FormsAuthenticationTicket authTicket = id.Ticket; if (string.IsNullOrEmpty(authTicket.UserData) || authTicket.UserData.Trim() == string.Empty) { // SupplyAccountDAL supplyAccountDAL = new SupplyAccountDAL(); // SupplyAccount user = supplyAccountDAL.GetModel(new SupplyAccount() { SupplyAccountID = Convert.ToInt32(app.Context.User.Identity.Name) }); SupplyAccount user = new SupplyAccount(); UserIdentity userIdentity = new UserIdentity(user, true); app.Context.User = new Principal(userIdentity); } } } catch { app.Context.User = new Principal(); FormsAuthentication.SignOut(); } }
/// <summary> /// 用户验证 /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> public static bool AuthenticateUser(string loginName, string password, ref string errorMsg, bool rememberMe = false, string currentIp = null) { try { //SupplyAccountDAL supplyAccountDAL = new SupplyAccountDAL(); if (string.IsNullOrWhiteSpace(currentIp)) { currentIp = GetWebClientIp(); } string curSite = HttpContext.Current.Request.Url.Host; SupplyAccount user = new SupplyAccount(); //supplyAccountDAL.Login(loginName, EncryptHelper.MD5Encrypt32(password)); if (user != null) { UserIdentity userIdentity = new UserIdentity(user, true); HttpContext.Current.User = new Principal(userIdentity); string accountJson = JsonConvert.SerializeObject(userIdentity); // FormsAuthentication.SetAuthCookie(user.SupplyAccountID.ToString(), rememberMe); //这是一个很尴尬的写法 //序列化account对象 // string accountJson = JsonConvert.SerializeObject(userIdentity); // 创建用户票据 var ticket = new FormsAuthenticationTicket(1, userIdentity.UserName, DateTime.Now, DateTime.Now.AddDays(1), false, accountJson); //加密 string encryptAccount = FormsAuthentication.Encrypt(ticket); //创建cookie var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptAccount) { HttpOnly = true, Secure = FormsAuthentication.RequireSSL, Domain = FormsAuthentication.CookieDomain, Path = FormsAuthentication.FormsCookiePath }; //写入Cookie HttpContext.Current.Response.Cookies.Remove(cookie.Name); HttpContext.Current.Response.Cookies.Add(cookie); return(true); } else { errorMsg = "账号或密码有误,请重新输入"; return(false); } } catch (Exception e) { throw new Exception(String.Format("登陆失败 {0}:{1}", loginName, e.Message), e); } }
public UserIdentity(SupplyAccount user, bool?isAuthenticated) : this() { if (user != null) { UserID = user.SupplyAccountID; UserName = user.SupplierAccount; LoginName = user.SupplierAccount; IsAdmin = true; UserType = user.UserType.Value; SupplierID = user.SupplierID; } if (isAuthenticated.HasValue) { IsAuthenticated = isAuthenticated.Value; } }