您好,欢迎来到[编程问答]网站首页   源码下载   电子书籍   软件下载   专题
当前位置:首页 >> 编程问答 >> .NET >> Session 求session和cookie联合登录的思路

Session 求session和cookie联合登录的思路

来源:网络整理     时间:2016/7/8 8:12:09     关键词:Session

关于网友提出的“Session 求session和cookie联合登录的思路”问题疑问,本网通过在网上对“Session 求session和cookie联合登录的思路”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:

问题:Session 求session和cookie联合登录的思路
描述:

想做网站登录,单一的Session和单一的cookie都有各自的弊端,不知是不是高手们做网站登录时是否都会将它们联合?
如果是的话,联合的方法又是什么?
是不是服务器端一直使用session,在session超时和丢失的时候,用cookie来获取重新连接Session?
最好能给出用户登录的关键类别代码。
问题比较简单,有劳各位高手。 (请不要回答session和coocke各有各的好,一个在服务器端比较安全,一个在客户端比较危险,或者一个比较好资源容易丢失,一个比较方便使用等等的回答,网上全部都是,但没有解决关键问题的。我想知道的是他们如何联合使用构成一个正常的登录)


解决方案1:


public static bool Admin()
    {
        try
        {
            HttpCookie mycookie = HttpContext.Current.Request.Cookies["admin"];
            if (mycookie == null)
            {
                JScript.Alertto1("为了系统安全,请您重新登陆!", "../denglu.html");
                return false;
            }
            else
            {
                if (HttpContext.Current.Session["admin"] == null)
                {
                    HttpContext.Current.Session["admin"] = mycookie.Value;//读取Cookie中用户登录信息   
                    return true;
                }
                else
                {
                    return true;
                }
            }
        }
        catch (Exception ex)
        {
            JScript.Alertto1("为了系统安全,请您重新登陆!", "../denglu.html");
            return false;
        }
    }
 
解决方案2:

引用 18 楼 jason_dct 的回复:
联合使用的意义 不太大吧。
----session需要借助cookie才能正常如果客户端,完全禁止cookie,session将失效。http是无状态的协议,客户每次读取web页面时,服务器都打开新的会话,而且服务器也不会自动维护客户的上下文信息。
-----  原理 
session是以cookie或URL重写为基础的,默认使用cookie来实现,系统会创造一个名为JSESSIONID的输出cookie,我们叫做session cookie,以区别persistent cookies,也就是我们通常所说的cookie,注意session cookie是存储于浏览器内存中的,并不是写到硬盘上的,这也就是我们刚才看到的JSESSIONID,我们通常情是看不到JSESSIONID的,但是当我们把浏览器的cookie禁止后,web服务器会采用URL重写的方式传递Sessionid,我们就可以在地址栏看到sessi /> ----------结论
Session和cookie作为两种并列的http传送信息的方式,session cookies位于服务器端,persistent cookie位于客户端,可是session又是以cookie为基础的,在iis里 一般可用性是同时的。
--------------------------------手酸了 不写了

问题就在于,.NET的session不靠谱,程序池重启的时候,session会丢失,webconfig修改,appcode修改,重启时间到以及程序的错误,内存满等等,都会引起程序池重启,另外一点,比如有人登陆要保存登陆状态1个月,你放session里能做到吗
?这就是为什么还要cookie里保存的原因,但cookie不能存敏感信息,所以需要从cookie里读出信息,并验证,再放入session中 解决方案3:

联合使用的意义 不太大吧。
----session需要借助cookie才能正常如果客户端,完全禁止cookie,session将失效。http是无状态的协议,客户每次读取web页面时,服务器都打开新的会话,而且服务器也不会自动维护客户的上下文信息。
-----   原理  
session是以cookie或URL重写为基础的,默认使用cookie来实现,系统会创造一个名为JSESSIONID的输出cookie,我们叫做session cookie,以区别persistent cookies,也就是我们通常所说的cookie,注意session cookie是存储于浏览器内存中的,并不是写到硬盘上的,这也就是我们刚才看到的JSESSIONID,我们通常情是看不到JSESSIONID的,但是当我们把浏览器的cookie禁止后,web服务器会采用URL重写的方式传递Sessionid,我们就可以在地址栏看到sessi /> ----------结论
Session和cookie作为两种并列的http传送信息的方式,session cookies位于服务器端,persistent cookie位于客户端,可是session又是以cookie为基础的,在iis里 一般可用性是同时的。
--------------------------------手酸了 不写了

解决方案4:

刚才是登陆的思路,登陆后,每个页面都继承一个BLL.Admin.PageBase.cs页面,来判断是否登陆以及是否有权限查看该页
BLL.Admin.PageBase.cs
using System;
using System.Data;
namespace BLL.Admin.PageBase
{
    /// 


    /// AdminPageBase 的摘要说明。
    /// 

    public class AdminPageBase : System.Web.UI.Page
    {
        private static string strLogOutURL = "/Admin/frame/logout.aspx";
        /// 
        /// 是否在PageBase中做权限判断开关。
        /// 使用方法:重载OnInit函数,在其中将该值改为true可关闭用户权限检查
        /// 

        protected bool IgnoreCheckPower = false;
        private void PageBase_Load(object sender, System.EventArgs e)
        {
            #region 通过IgnoreCheckPower确定是否进行PageBase中权限判断动作
            IgnoreCheckPower = false;
            #endregion
            if (!IgnoreCheckPower)
            {
                if (!string.IsNullOrEmpty(Convert.ToString(Session["CurrentTypeID"])))
                {
                    CheckPower(Session["CurrentTypeID"].ToString());
                }
                else
                {
                    Server.Execute(strLogOutURL);
                }
            }
        }
        private void PageBase_Init(object sender, System.EventArgs e)
        {
            CheckAdminID();
        }
        #region 用户权限验证函数
        /// 
        /// 用户权限判断:依据用户权限表(登陆时信息已提取到Session["TypeID"]中)做用户权限判断
        /// 

        /// 待判断页面的ModalTypeID
        /// 用户是否有权限。实际用户没有权限时,已直接转向登陆页
        public bool CheckPower(string TypeID)
        {
            bool Flag = false;
            if (Session["TypeID"] != null)
            {
                string[] arrTypeID = Session["TypeID"].ToString().Split(',');
                for (int i = 0; i < arrTypeID.Length; i++)
                {
                    if (arrTypeID[i] == TypeID)
                    {
                        Flag = true;
                        break;
                    }
                }
            }
            if (Flag == false)
            {
                //说明没有相应的权限
                System.Web.HttpContext.Current.Response.Redirect("/Admin/frame/blank.html");
            }
            return Flag;
        }
        #endregion
        #region PageBase事件映射代码
        override protected void OnInit(EventArgs e)
        {
            this.Init += new System.EventHandler(this.PageBase_Init);
            this.Load += new System.EventHandler(this.PageBase_Load);
            base.OnInit(e);
        }
        #endregion
        #region AdminID获取和检查
        /// 
        /// 1、将Request传入的AdminID保存到Session["AdminID"]中
        /// 2、无Session["AdminID"]情况,判断cookie和数据库密钥是否相同,不相同重新登陆,相同就重新赋予session
        /// 

        private void CheckAdminID()
        {
            if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["TypeID"])))
            {
                Session["CurrentTypeID"] = Request.QueryString["TypeID"];
            }
            string strAdminID = Request.QueryString["AdminID"];
            if (strAdminID != null)
            {
                Session["AdminID"] = Convert.ToInt32(strAdminID);
            }
            if (Session["AdminID"] == null)
            {
                //先检查cookie是否存在,如果不存在,那么重新登陆,如果存在,那么和数据库密钥比较,正确了重新写session
                int AdminID = 0;
                string SecurityKey = String.Empty;
                //先检查cookie状态,如果cookie不存在,返回并提示登陆,如果cookie存在,进行cookie验证
                System.Web.HttpCookie MyCookie = System.Web.HttpContext.Current.Request.Cookies["admin.com_login"];
                if (MyCookie == null || String.IsNullOrEmpty(MyCookie.Value) || MyCookie["AdminID"] == null || String.IsNullOrEmpty(MyCookie["SecurityKey"]))
                {
                    //显示登陆状态
                    Server.Execute(strLogOutURL);
                }
                else
                {
                    AdminID = Convert.ToInt32(MyCookie["AdminID"]);
                    SecurityKey = MyCookie["SecurityKey"].ToString();
                    DataTable dt = BLL.Admin.Login.dbLogin.CheckSecurityKey(AdminID, SecurityKey);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        //写入session
                        System.Web.HttpContext.Current.Session["AdminID"] = dt.Rows[0]["AdminID"].ToString();
                        System.Web.HttpContext.Current.Session["Password"] = dt.Rows[0]["SecurityKey"].ToString(); ;
                        #region 获取指定AdminID拥有的模块权限IDs,保存到Session["TypeID"]中
                        DataTable dtGetTypeID = BLL.Admin.Login.dbLogin.GetModalTypeList(Convert.ToInt32(System.Web.HttpContext.Current.Session["AdminID"]), 1);
                        string strTypeID = String.Empty;
                        for (int i = 0; i < dtGetTypeID.Rows.Count; i++)
                        {
                            strTypeID += dtGetTypeID.Rows[i]["TypeID"] + ",";
                        }
                        strTypeID = strTypeID.TrimEnd(',');
                        System.Web.HttpContext.Current.Session["TypeID"] = strTypeID;
                        #endregion
                    }
                    else
                    {
                        Server.Execute(strLogOutURL);
                    }
                }
                return;
            }
        }
        #endregion
       
    }
}
需要判断权限的页面,继承刚才的cs页面
public partial class Admin_AdManager_tongzhiview : BLL.Admin.PageBase.AdminPageBase
思路基本这样

解决方案5:

以前csdn上的一个例子
登录页面


protected void LoginButton_Click(object sender, EventArgs e)
    {
        if (this.userName.Text == "1" && this.password.Text == "1")
        {
            this.msgLabel.Text = "OK";
            // 设置登录成功后的 Session
            Session["LoginSession"] = "Session OK";
            // 设置登录成功后的 Cookie
            HttpCookie cookie = new HttpCookie("LoginCookies");
            cookie.Expires = DateTime.Now.AddMinutes(30); //DateTime.Now.AddDays(1);
            cookie.HttpOnly = false;
            cookie.Values.Add("LoginCookie", "Cookie OK");
            Response.AppendCookie(cookie);
            // Response.Redirect, Server.Transfer, Server.Execute
            //  这3中页面导航的方法,WebClient.UploadData 都可以成功下载目标页面,
            //  可以根据实际情况选择其中一种方法
            //Server.Transfer("LoginOK.htm");  // 保持地址栏 URL 不变
            //Server.Execute("LoginOK.htm");   // 保持地址栏 URL 不变,会把原页面的内容附加在 Server.Execute 页面的后面
            //Response.Redirect("LoginOK.htm");// 会使 AutoPost 程序中得不到cookie: string cookie = webClient.ResponseHeaders.Get("Set-Cookie"); cookie 为 null。
            Response.Redirect("LoginOK.htm");
        }
        else
            this.msgLabel.Text = "Error!";
    }

跳转页

protected void Page_Load(object sender, EventArgs e)
    {
        string loginSession;
        HttpCookie loginCookies = Request.Cookies["LoginCookies"];
        if (Session["LoginSession"] != null && loginCookies != null)
        {
            loginSession = Session["LoginSession"].ToString();
            string formatString = "LoginSession={0}, LoginCookie={1}! 登录成功!";
            Label1.Text = String.Format(formatString, loginSession, loginCookies.Values["LoginCookie"]);
        }
        else if (Session["LoginSession"] == null && loginCookies == null)
            Label1.Text = "Session Error, Cookies Error! 登录失败!";
        else if (Session["LoginSession"] == null)
            Label1.Text = "Session Error! 登录失败!";
        else if (loginCookies == null)
            Label1.Text = "Cookies Error! 登录失败!";
    }

以上介绍了“Session 求session和cookie联合登录的思路”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/2406448.html

Session相关图片

Session相关文章