SSO:一个用户在同一个网站只能进行唯一登录功能,用于避免同一用户和密码在不同地进行登录。
实现原理:利用Web缓存,把已经登录的用户信息保存在cache对象中,设置其过期时间为session的失效时间,一旦Session失效,Cache对象也就过期了
实现步骤:
1.新建Asp.net Web Appplication
2.放置一个登录按钮
主要程序代码如下
protected void Button1_Click(object sender ,EventHanler e)
{
int i =checkLogin(this.txtUserName.text,this.txtUserPwd.text);
if(i>0)
{
string strKey=this.txtUserName+"_"+txtUserPwd.text;
string strUser=Cache["strKey"].ToString();
if(strUser=="")
{
TimeSpan setTimeOut= new TimeSpan(0,0,HttpContext.Current.Session.Timeout,0,0);
HttpContext.Current.Cache.Insert(strKey,null,DateTime.MaxValue,setTimeout,CacheItemPriority.NotRemovale,null);
Session["User"]=strKey;
//首次登录成功
Response.Write("首次登录成功!");
}
else
{
Response.Write("<h1 style='color:Red'>已经登录过了");
return;
}
}
else
{
Response.Write("用户名和密码有误!");
}
}
//验证登录
public int checkLogin(string loginName, string loginPwd)
{
SqlConnection con = new SqlConnection("Server=(local);database=db_18;Uid=sa;Pwd=");
SqlCommand myCommand = new SqlCommand("select count(*) from tb_Admin where userID="@loginName" and pwd="@loginPwd"", con);
myCommand.Parameters.Add(new SqlParameter("@loginName", SqlDbType.NVarChar, 20));
myCommand.Parameters["@loginName"].Value = loginName;
myCommand.Parameters.Add(new SqlParameter("@loginPwd", SqlDbType.NVarChar, 20));
myCommand.Parameters["@loginPwd"].Value = loginPwd;
myCommand.Connection.Open();
int i = (int)myCommand.ExecuteScalar();
myCommand.Connection.Close();
return i;
}