1. asp.net實現單點登陸

來源:互聯網
上載者:User

一、簡單說明:

單點登入(Single Sign On)簡稱SSO,是目前比較流行的企業業務整合的解決方案之一。在開發企業門戶網站或電子商務系統時,設計一個使用者只能在同一個網站進行唯一登入的功能,可以避免一個使用者名稱和密碼在多個地址進行登入。

二、技術要點:

Cache對象主要使用者Web應用程式的緩衝,對於每個應用程式都需要建立Cache對象的一個執行個體,並且只要對應的應用程式定義域保持活動,該執行個體便保持有效,有段Cache對象執行個體的所有資訊都需要通過HttpContext對象的Cache屬性或Page對象的Cache屬性來提供。

 

三、代碼實現

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Caching;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnLogin_Click(object sender, EventArgs e)
{
int i = this.checkLogin(txtName.Text, txtPwd.Text);
if (i > 0)
{
// 作為唯一標識的str_Key,應該是唯一的,這可根據需要自己設定規則。
// 做為測試,這裡用使用者名稱和密碼的組合來做標識;也不進行其它的錯誤檢查。
// 產生str_Key
string str_Key = txtName.Text + "_" + txtPwd.Text;
// 得到Cache中的給定str_Key的值
string str_User = Convert.ToString(Cache[str_Key]);
// Cache中沒有該str_Key的項目,表名使用者沒有登入,或者已經登入逾時
if (str_User == String.Empty)
{
// TimeSpan建構函式,用來重載版本的方法,進行判斷是否登入。
TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
HttpContext.Current.Cache.Insert(str_Key, str_Key, null, DateTime.MaxValue, SessTimeOut, CacheItemPriority.NotRemovable, null);
Session["User"] = str_Key;
// 首次登入成功
Response.Write("<h2 style='color:red'>你好,登入成功!");
}
else
{
// 在 Cache 中存在該使用者的記錄,表名已經登入過,禁止再次登入
Response.Write("<h2 style='color:red'>抱歉,您好像已經登入了!");
return;
}

}
else
{
Response.Write("使用者名稱稱或密碼錯誤!!!");
}
}
protected void btnCandel_Click(object sender, EventArgs e)
{
txtName.Text = "";
txtPwd.Text = "";
}
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 系統管理員表 where 使用者名稱稱=@loginName and 密碼=@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;
}
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.