自动登录、记住我(保存登陆状态)实现

自动登录、记住我(保存登陆状态)实现:
保存在客户端
不能用session,可以用cookies保存

实现方式:
第一种方法:
可以把SessionId(GUID)放到cookies中,但

这样为了让用户下次访问我们网站时,知道这

个sessionId对应的是哪一个用户,我们还要在

数据库中建张表。
表字段:
主键,UserId  SessionId  时间

缺点:不能在两台机器上同时保存


第二种方法:
把UserId放cookies中  密码(加密)
相对于第一种方法优点:多台机器可以保存
缺点:不安全,密码放到了客户端。

 

第二种方法实现代码:

页面加载读取Cookie判断,正确写入Session,转向

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.Cookies["cUser"] != null && Request.Cookies["cPwd"] != null)
                {
                    string cUser = Request.Cookies["cUser"].Value;
                    string cPwd = Request.Cookies["cPwd"].Value;

                    string sqlPwd = "";
                    BookShop.Model.User oneUser = bll.Exists(cUser);
                    if (oneUser != null)
                    {
                        #region MyRegion
                        //说明存在cUser
                        if (cPwd.Length > 2)//防止用户修改Cookie中的密码报错
                        {
                            string salt = cPwd.Substring(0, 2);
                            sqlPwd = oneUser.LoginPwd;

                            sqlPwd = Encrypt(sqlPwd, salt);
                            if (cPwd == sqlPwd)
                            {
                                //保存Session状态
                                Session["user"] = oneUser;
                                //转向
                                #region MyRegion
                                if (Request.QueryString["returnUrl"] == null)
                                {
                                    //登陆成功,转向首页
                                    Response.Redirect("/member/ShowMessage.aspx?returnUrl=" + Server.UrlEncode("/Default.aspx") + "&msg=" + Server.UrlEncode("自动登陆成功") + "&txt=" + Server.UrlEncode("转向首页"));

                                }
                                else
                                {
                                    //登陆成功,转向上次访问页面
                                    string returnUrl = Request.QueryString["returnUrl"];
                                    Response.Redirect(returnUrl);
                                }
                                #endregion
                            }
                        }
                        #endregion

                    }
                    //如果Cookies出错...清除cookie
                    ClearLoginCookie();
                }
               


            }

        }

//页面登陆

 protected void btnLogin_Click(object sender, ImageClickEventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }
            string uid = txtLoginId.Text.Trim();
            string pwd = txtLoginPwd.Text.Trim();
            BookShop.Model.User oneUser;
            UserManager bll = new UserManager();
            bool result = bll.Login(uid, pwd, out oneUser);
            if (result)
            {
                //保存session
                Session["user"] = oneUser;

                //保存Cookie状态
                if (cbAutoLogin.Checked)
                {
                    HttpCookie cUser = new HttpCookie("cUser", uid);
                    HttpCookie cPwd = new HttpCookie("cPwd", Encrypt(oneUser.LoginPwd));
                    cUser.Expires = DateTime.Now.AddYears(10);
                    cPwd.Expires = DateTime.Now.AddYears(10);
                    Response.Cookies.Add(cUser);
                    Response.Cookies.Add(cPwd);
                }

                if (Request.QueryString["returnUrl"] == null)
                {
                    //登陆成功,转向首页
                    Response.Redirect("/Default.aspx");
                }
                else
                {
                    //登陆成功,转向上次访问页面
                    string returnUrl = Request.QueryString["returnUrl"];
                    Response.Redirect("/member/ShowMessage.aspx?returnUrl=" + HttpContext.Current.Server.UrlEncode(returnUrl) + "&msg=" + Server.UrlEncode("登陆成功") + "&txt=" + Server.UrlEncode("转向上次访问页面"));
                }

}
            else
            {
                //登陆失败,提示错误信息
                Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "alert('用户名或密码错误!');", true);
            }


        }

 

/// <summary>
        /// 对密码进行MD5加密
        /// </summary>
        /// <param name="pwd"></param>
        /// <returns></returns>
        protected string Encrypt(string pwd)
        {
            return Encrypt(pwd, null);
        }

/// <summary>
        /// MD5加密方法扩展
        /// </summary>
        /// <param name="pwd"></param>
        /// <returns></returns>
        protected string Encrypt(string pwd, string salt)
        {
            //加密规则: salt+md5(salt+md5(pwd+"zfx"))
           

            MD5 md5 = MD5.Create();//MD5加密方法
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(pwd + "zfx");
            buffer = md5.ComputeHash(buffer);
            string str = "";
            for (int i = 0; i < buffer.Length; i++)
            {
                str += buffer[i].ToString("X2");
            }

            if (salt == null)
            {
                Random r = new Random();
                salt = ((char)(r.Next(65, (65 + 26)))).ToString() + ((char)(r.Next(65, (65 + 26)))).ToString();
            }
            str = salt + str;
            str = CommenCodes.CommenCodes.Md5(str); //调用其他类库中 MD5实现方法,具体实现见本方法之前
            return (salt + str);
        }

 

        /// <summary>
        /// (在服务器端)清除客户端cookie
        /// </summary>
        private void ClearLoginCookie()
        {
          //在服务器端清除客户端cookie
            HttpCookie cUser = new HttpCookie("cUser");//新建两个跟之前同名的cookie,用于覆盖客户端的cookie
            HttpCookie cPwd = new HttpCookie("cPwd");
            cUser.Expires = DateTime.Now.AddYears(-10);//设置过期时间为过期
            cPwd.Expires = DateTime.Now.AddYears(-10);
            Response.Cookies.Add(cUser);
            Response.Cookies.Add(cPwd);
       
        }


自动登录绝对不安全,有安全隐患
进入网站后,对于关键步骤再次要求用户输入密码

posted @ 2015-01-30 13:39  三小  阅读(778)  评论(0编辑  收藏  举报