登录必备

       private void LoadCookie()
        {
            var cookie = this.Request.Cookies["LoginName"];
            if (cookie == null || String.IsNullOrEmpty(cookie.Value))
            {
                this.ckbSave.Checked = false;
                return;
            }
            this.txtUsername.Value = cookie.Value;
            this.ckbSave.Checked = true;

        }


     protected void btnLogin_Click(object sender, EventArgs e)
          {
            string message;
            int userId = 0; 
            bool verify = UserHelper.Entry(this.txtUsername.Value.Trim(), this.txtPassword.Value.Trim(), out message, out userId);
            if (!verify)
            {
                this.litError.Text = message;
                return;
            }

            UserHelper.SetCookie(userId);
            this.Response.Redirect(redirecturl);
        }


       public static void SetCookie(int userId)
        {
            Guid token = Guid.NewGuid();
            HttpContext context = HttpContext.Current;
            //保存登录信息
            EntryLog log = EntryLogData.CreateOrUpdate(new EntryLog
            {
                UserId = userId,
                LoginIp = context.Request.UserHostAddress,
                Token = token
            });
            //删除缓存
            caching.Remove(userId);
            //设置唯一标识
            HttpCookie cookie = new HttpCookie(COOKIE_Token, token.ToString());
            //cookie.Expires = DateTime.Now.Add(FormsAuthentication.Timeout);
            cookie.Path = FormsAuthentication.FormsCookiePath;
           // cookie.Domain = FormsAuthentication.CookieDomain;
            cookie.HttpOnly = true;
            context.Response.Cookies.Add(cookie);
            FormsAuthentication.SetAuthCookie(userId.ToString(), true);
        }

       <authentication mode="Forms">
       <forms loginUrl="/Login.aspx" timeout="20" name=".EasytourAppDev" defaultUrl="Default.aspx" protection="All" enableCrossAppRedirects="true" />
       </authentication>


      /// <summary>
        /// 用户注销
        /// </summary>
        public static void Logout()
        {
            HttpContext context = HttpContext.Current;
            //唯一标识
            HttpCookie tokenCookie = new HttpCookie(COOKIE_Token, "");
            tokenCookie.Expires = DateTime.Now.AddDays(-1);
            context.Response.Cookies.Add(tokenCookie);
            context.Response.Cookies.Remove(COOKIE_Token);
            //登录Cookie
            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, "");
            authCookie.Expires = DateTime.Now.AddYears(-1);
            context.Response.Cookies.Add(authCookie);
            //Asp.net
            HttpCookie aspNetCookie = new HttpCookie("ASP.NET_SessionId", "");
            aspNetCookie.Expires = DateTime.Now.AddYears(-1);
            context.Response.Cookies.Add(aspNetCookie);


            FormsAuthentication.SignOut();
            HttpContext.Current.Session.Abandon();
            context.Response.Redirect("Login.aspx");


        }


        #region 获取当前登录用户信息 
        /// <summary>
        /// 获取当前登录用户的ID
        /// </summary>
        /// <returns>当前登录用户的ID</returns>
        public static User CurrentUser(int userId = 0)
        {
            var identity = HttpContext.Current.User.Identity;
            if (!identity.IsAuthenticated)
            {
                HttpContext.Current.Response.Redirect(FormsAuthentication.LoginUrl);
            }
            if (userId == 0)
            {
                userId = int.Parse(identity.Name);
            }
            User user = UserBusiness.GetUser(userId);


            if (user == null || user.Id != userId || !VerifyToken(userId))
            {
                if (!HttpContext.Current.Response.IsRequestBeingRedirected)
                {
                    HttpContext.Current.Response.Redirect(FormsAuthentication.LoginUrl);
                }


            }
            // throw new Exception("用户信息为空");


            return user;
        }


       /// <summary>
        /// 验证唯一标识
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        private static bool VerifyToken(int userId)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[COOKIE_Token];
            if (cookie == null)
            {
                return false;
            }
            EntryLog log = caching.Get(userId);
            if (log == null)
            {
                return false;
            }
            Guid token;
            if (!Guid.TryParse(cookie.Value, out token))
            {
                return false;
            }
            if (token != log.Token)
            {
                return false;
            }
            return true;
        }

转载于:https://www.cnblogs.com/wangyhua/p/4050599.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值