public virtual void SignIn(s_User user, bool createPersistentCookie) { var now = DateTime.UtcNow.ToLocalTime(); //01 实例化一个form表单身份验证票证 //FormsAuthenticationTicket(int version, string name, DateTime issueDate, DateTime expiration, bool isPersistent, string userData, string cookiePath); var ticket = new FormsAuthenticationTicket( 1 /*version*/, //票证的版本号 user.Nickname, //用户名 now, //发生时间 now.Add(_expirationTimeSpan), //过期时间,通常用FormsAuthentication.Timeout作默认值 createPersistentCookie, //true存储在cookie,false存储在url,这个用户选择,“记住我” user.Email, //用户数据,这里只保存了email FormsAuthentication.FormsCookiePath); //Cookie存放路径,通常用FormsAuthentication.FormsCookiePath作默认值 //02 将票证加密成适合cookie保存的字符串 string encryptedTicket = FormsAuthentication.Encrypt(ticket); //03 将加密后的字符串写入cookie HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); cookie.HttpOnly = true; //不允许客户端脚本访问cookie,仅限http访问 if (ticket.IsPersistent)//如果票证需要持久化,指定cookie过期时间 { cookie.Expires = ticket.Expiration; } //使用https传输此cookie cookie.Secure = FormsAuthentication.RequireSSL; cookie.Path = FormsAuthentication.FormsCookiePath; if (FormsAuthentication.CookieDomain != null) { cookie.Domain = FormsAuthentication.CookieDomain; } _httpContext.Response.Cookies.Add(cookie); _cachedUser = user; //如果想用默认的方式处理,不写上面那么多:FormsAuthentication.SetAuthCookie(loginName, true); } //验证当前通过验证的用户 public virtual s_User GetAuthenticatedUser() { //如果有缓存的用户,就返回缓存的用户 //如果是基于http会话级的生命周期注入方式,则是可以这样写的 if (_cachedUser != null) return _cachedUser; if (_httpContext == null || //如果httpContext为空 _httpContext.Request == null || // 或httpContext.Request为空 Request.IsAuthenticated为假就返回 空 !_httpContext.Request.IsAuthenticated || // 或或httpContext.Request.IsAuthenticated = false !(_httpContext.User.Identity is FormsIdentity)) //_httpContext.User.Identity的票证不是 FormsIdentity { return null; // 都返回null, 即用户验证失败 } //获取会话中的表单身份验证票证[这个user封装了读cookie,解密cookie,验证转换的过程] var formsIdentity = (FormsIdentity)_httpContext.User.Identity; //从formsIdentity.Ticket.UserData取email var userEmail = formsIdentity.Ticket.UserData; //如果email验证失败,则验证失败 if (String.IsNullOrWhiteSpace(userEmail)) return null; //用email去查询数据库,获取user var user = _userService.GetUserByEmail(userEmail); //如果是合法用户,返回当前合法用户 if (user != null && user.Active ) _cachedUser = user; return user; } public virtual void SignOut() { _cachedUser = null; FormsAuthentication.SignOut(); }
时间: 2024-10-01 04:02:48