ASP.Netワンポイントログインを実現

2953 ワード


一、簡単な説明:
Single Sign OnはSSOと略称され、現在流行している企業業務統合のソリューションの一つである。企業ポータルサイトや電子商取引システムを開発する際、1人のユーザーが同じサイトで唯一ログインできる機能を設計し、1人のユーザー名とパスワードが複数のアドレスでログインすることを避けることができます。

二、技術の要点:
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 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; // 最初のログインに成功しました。Write("<h 2 style='color:red'>こんにちは、ログイン成功!");}Else{//Cacheにはそのユーザのレコードが存在し、テーブル名は既にログイン済みであり、Response.Writeへの再ログインは禁止されている(「<h 2 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("selectcount(*)fromシステム管理者テーブルwhereユーザー名=@loginName andパスワード=@loginPwd",con);myCommand.Parameters.Add(new)myCommand.Parameters.Add 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; }}