单用户登录

如果要实现单点登录,统一的认证系统是SSO的前提之一。简单说说单用户登录。怎么在同一个账号的下,后一个登录的把前一个踢掉

方法一:

1.在web.config文件的system.web 结点加<sessionState mode="InProc"></sessionState>这样可以触发global.asax文件中的session_end事件

2.global.asax文件,Session_End 事件,在Application存储验证字段online

Hashtable hash = (Hashtable)Application["online"];
if (hash[Session.SessionID] != null){
  hash.Remove(Session.SessionID);
}
Application["online"] = hash;

3.登录的时候,给online赋值,记录用户id,登录ip,登录时间等信息,如果用户id相同就更新online的值

    private void isLogin()
    {
        Hashtable h = (Hashtable)Application["online"]; if (h == null) { h = new Hashtable(); }
        //验证用户是否在Application中存在(是否在线)      
        IDictionaryEnumerator e1 = h.GetEnumerator();
        while (e1.MoveNext())
        {
            if (checkCookie(e1.Value.ToString()))
            {
                h.Remove(e1.Key);
                break;
            }
        }

        //生成服务端标识值              
        DateTime now = DateTime.Now;
        string cookieValue = now.Year.ToString() + now.Month.ToString() + now.Day.ToString() + now.Hour.ToString() + now.Minute.ToString() + now.Second.ToString() + now.Millisecond.ToString();
        //把userid + 标识值写入全局变量表       
        h[Session.SessionID] = _user.Guid.Trim() + "," + cookieValue;
        Application["Online"] = h;

         //把标识值写入客户端cookie
         Response.Cookies["hqs"].Value = cookieValue;
         Response.Cookies["hqs"].Expires = DateTime.Now.AddDays(1);

       Session[System.Web.Configuration.WebConfigurationManager.AppSettings["LOGIN_USER"]] = _user.Guid;
    }

4.当用户请求带有Session页面的,获取Session和Application,和本地存储的密钥对比,如果不相同就结束当前用户的会话,这样就可以实现单用户登录

            Object obj = Session[System.Web.Configuration.WebConfigurationManager.AppSettings["LOGIN_USER"]];
            if (obj == null)
            {
                //session为空,转重新登录页面
                Response.Redirect(this.RootPath + this._redirect_url);
            }

            //如果会话中的标识不相同,就是账号在其他地方登录,结束会话
            Hashtable h = (Hashtable)Application["online"]; if (h == null) { h = new Hashtable(); }
            IDictionaryEnumerator e1 = h.GetEnumerator();
            while (e1.MoveNext())
            {
                if (Request.Cookies["hqs"] != null)
                {
                    string cookieValue = Request.Cookies["hqs"].Value;
                    char[] sp = new char[1] { ',' };
                    string LoginUserid = e1.Value.ToString().Split(sp)[0].ToString();
                    string LoginCookie = e1.Value.ToString().Split(sp)[1].ToString();

                    if (LoginUserid == Convert.ToString(obj) && LoginCookie != cookieValue)
                    {
                        Session.RemoveAll();
                        //结束会话,转重新登录页面
                        Response.Redirect(this.RootPath + this._redirect_url);
                    }
                }
            }
原文地址:https://www.cnblogs.com/SilverWolf/p/9767792.html