之前看过几篇关于asp.net单点登录的文章,大概单点登录有两种,一种是登录一个入口就可以进多个系统不需要多次登录,一种是一个系统一个用户只能一个人同时在线,本文主要讨论后者.
那天要写单点登录时,不知道怎么回事以前的那些关于单点登录的文章都找不到了,只好凭着一点记忆和想像写了出来,
思路是这样的:
系统有一个hashtable保存在线用户的id,guid,当一个用户登录上来后产生一个guid然后加上用户id在这个hashtable里存一次,然后再在Session里也保存一次,
当第二次用户登录上来后,会再产生一个guid,保存到hashtable和Session中覆盖上一次登录的值,然后在页面检测用户的时候判断当前用户的Session和系统的hashtable里的值是否一致,如果不一致说明他已在登录第二次,那就给当前用户提示已经在别处登录了,然后页面转向到登页面,销毁Session,
1.登录的时候
1
//
检查身份
2 if (myBUStaff.ID.Length > 0 )
3 {
4 // 单点登陆
5 string UserKey = Guid.NewGuid().ToString();
6 if (CommonMethod.CurrentUser.ContainsKey(myBUStaff.ID))
7 {
8 CommonMethod.CurrentUser[myBUStaff.ID] = UserKey;
9 Session["UserKey"] = UserKey;
10 }
11 else
12 {
13 CommonMethod.CurrentUser.Add(myBUStaff.ID, UserKey);
14 Session["UserKey"] = UserKey;
15 }
2.在检查用户时
2 if (myBUStaff.ID.Length > 0 )
3 {
4 // 单点登陆
5 string UserKey = Guid.NewGuid().ToString();
6 if (CommonMethod.CurrentUser.ContainsKey(myBUStaff.ID))
7 {
8 CommonMethod.CurrentUser[myBUStaff.ID] = UserKey;
9 Session["UserKey"] = UserKey;
10 }
11 else
12 {
13 CommonMethod.CurrentUser.Add(myBUStaff.ID, UserKey);
14 Session["UserKey"] = UserKey;
15 }
if
(Session[
"
UserKey
"
]
==
null
||
CommonMethod.CurrentUser[Session[
"
OperatorID
"
].ToString()].ToString()
!=
Session[
"
UserKey
"
].ToString())
{
JsWrite("alert('您的帐号已经在别处登录,要继续请重新登录!'); window.parent.location.href = 'UILogOut.aspx';", "LogOut");
}
{
JsWrite("alert('您的帐号已经在别处登录,要继续请重新登录!'); window.parent.location.href = 'UILogOut.aspx';", "LogOut");
}
CommonMethod.cs
public
class
CommonMethod : System.Web.UI.Page
{
public static Hashtable CurrentUser = new Hashtable();
}
这里我直接就把他写成静态的.(可能这种方法不是很科学)
{
public static Hashtable CurrentUser = new Hashtable();
}
Global.asax
1
void
Session_End(
object
sender, EventArgs e)
2 {
3 // 在会话结束时运行的代码。
4 // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
5 // InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
6 // 或 SQLServer,则不会引发该事件。
7 try
8 {
9 string userid = Session["OperatorID"].ToString();
10 if (Session["UserKeny"].ToString() == CommonMethod.CurrentUser[userid].ToString())
11 {
12 CommonMethod.CurrentUser.Remove(userid);
13 }
14 }
15 catch
16 { }
17 }
2 {
3 // 在会话结束时运行的代码。
4 // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
5 // InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
6 // 或 SQLServer,则不会引发该事件。
7 try
8 {
9 string userid = Session["OperatorID"].ToString();
10 if (Session["UserKeny"].ToString() == CommonMethod.CurrentUser[userid].ToString())
11 {
12 CommonMethod.CurrentUser.Remove(userid);
13 }
14 }
15 catch
16 { }
17 }
然后再在web.config中加入session的有效期就可以了,一般我就设了10 分钟