//校验用户名密码(对Session匹配,或数据库数据匹配) private bool ValidateTicket(string encryptToken) { //解密Ticket var strTicket = FormsAuthentication.Decrypt(encryptToken).UserData; //从Ticket里面获取用户名和密码 var index = strTicket.IndexOf("&"); string userName = strTicket.Substring(0, index); string password = strTicket.Substring(index + 1); //取得session,不通过说明用户退出,或者session已经过期 //var token = HttpContext.Current.Session[userName]; var token = MembercacheHelper.GetCache(userName); if (token == null) { return(false); } //对比session中的令牌 if (token.ToString() == encryptToken) { return(true); } return(false); }
public TokenData Login(string userName, string password) { //实际场景应该到数据库进行校验 if (userName == "123" && password == "123") { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(0, userName, DateTime.Now, DateTime.Now.AddHours(1), true, string.Format("{0}&{1}", userName, password), FormsAuthentication.FormsCookiePath); //返回登录结果、用户信息、用户验证票据信息 var token = FormsAuthentication.Encrypt(ticket); //将身份信息保存在session中,验证当前请求是否是有效请求 //HttpContext.Current.Session[userName] = token; //将身份信息保存在Membercache中,验证当前请求是否是有效请求 MembercacheHelper.AddCache(userName, token, 10); try { var m = MembercacheHelper.GetCache(userName).ToString(); } catch (Exception ex) { TokenData tokendata1 = new TokenData() { ErrorCode = -1, Message = ex.ToString(), Token = "" }; return(tokendata1); } //写入cooike HttpCookie tokenCookie = new HttpCookie("Token"); tokenCookie.Value = token; tokenCookie.Expires = DateTime.Now.Add(new TimeSpan(24, 0, 0)); tokenCookie.Path = "/"; HttpContext.Current.Response.AppendCookie(tokenCookie); TokenData tokendata = new TokenData() { ErrorCode = 0, Message = "登录成功", Token = token }; return(tokendata); } else { TokenData tokendata = new TokenData() { ErrorCode = -1, Message = "用户名或密码错误", Token = "" }; return(tokendata); } }