把你不需要驗證的所有頁放在一個目錄下面,但是不用在那個目錄下面的WEB.CONFG中對FROMS驗證模式進行設置。只要在最上層的WEB.CONFIG中統一設置就可以了.比如下面的例子:
一、設置所有頁面都需要驗證
<system web>
<authentication mode="Forms">
??? <forms? loginUrl = "Lonin.aspx" name = ".ASPXFORMSAUTH"/>
</authentication>?
</system web>
二、再特別設置對某個目錄下的頁面不需要驗證(NoAuto為不需要驗證的頁面所在的目錄)
<location path="NoAuto">
??? <system.web>
????? <authorization>
??????? <allow users="*" />
????? </authorization>
??? </system.web>
</location>
一.?????
設置
web.config
相關選項
先啟用窗體身份驗證和默認登陸頁
,
如下。
<authentication mode="Forms">
?????? <forms loginUrl="default.aspx"></forms>
</authentication>
設置網站可以匿名訪問,如下
<authorization>
?????????? <allow users="*" />
</authorization>
然后設置跟目錄下的
admin
目錄拒絕匿名登陸,如下。注意這個小節在
System.Web
小節下面。
???? <location path="admin">
?????? <system.web>
?????????? <authorization>
????????????? <deny users="?"></deny>
?????????? </authorization>
?????? </system.web>
</location>
把
http
請求和發送的編碼設置成
GB2312,
否則在取查詢字符串的時候會有問題,如下。
<globalization requestEncoding="gb2312" responseEncoding="gb2312" />
設置
session
超時時間為
1
分鐘,并啟用
cookieless
,如下。
<sessionState mode="InProc" cookieless="true" timeout="1" />
為了啟用頁面跟蹤,我們先啟用每一頁的trace,以便我們方便的調試,如下。
<trace enabled="true" requestLimit="1000" pageOutput="true" traceMode="SortByTime" localOnly="true" />
二.?????
設置Global.asax文件
處理Application_Start方法,實例化一個哈西表,然后保存在Cache里
??? protected void Application_Start(Object sender, EventArgs e)
??? {
?????? Hashtable h=new Hashtable();
?????? Context.Cache.Insert("online",h);
}
??? 在Session_End方法里調用LogoutCache()方法,方法源碼如下
/// <summary>
??? /// 清除Cache里當前的用戶,主要在Global.asax的Session_End方法和用戶注銷的方法里調用? ??? /// </summary>
??? public void LogoutCache()
??? {
?????? Hashtable h=(Hashtable)Context.Cache["online"];
?? ??? if(h!=null)
?????? {
?????????? if(h[Session.SessionID]!=null)
?????????? h.Remove(Session.SessionID);
?????????? Context.Cache["online"]=h;
?????? }
}
三.?????
設置相關的登陸和注銷代碼
登陸前調用PreventRepeatLogin()方法,這個方法可以防止用戶重復登陸,如果上次用戶登陸超時大于1分鐘,也就是關閉了所有admin目錄下的頁面達到60秒以上,就認為上次登陸的用戶超時,你就可以登陸了,如果不超過60秒,就會生成一個自定義異常。在Cache["online"]里保存了一個哈西表,哈西表的key是當前登陸用戶的SessionID,而Value是一個ArrayList,這個ArrayList有兩個元素,第一個是用戶登陸的名字第二個元素是用戶登陸的時間,然后在每個admin目錄下的頁刷新頁面的時候會更新當前登陸用戶的登陸時間,而只admin目錄下有一個頁打開著,即使不手工向服務器發送請求,也會自動發送一個請求更新登陸時間,下面我在頁面基類里寫了一個函數來做到這一點,其實這會增加服務器的負擔,但在一定情況下也是一個可行的辦法.
/// <summary>
?????? /// 防止用戶重復登陸,在用戶將要身份驗證前使用
?????? /// </summary>
?????? /// <param name="name">要驗證的用戶名字</param>
?????? private void PreventRepeatLogin(string name)
?????? {
?????????? Hashtable h=(Hashtable)Cache["online"];
?????????? if(h!=null)
?????????? {
????????????? IDictionaryEnumerator e1=h.GetEnumerator();
????????????? bool flag=false;
????????????? while(e1.MoveNext())
????????????? {????????????????
????????????????? if((string)((ArrayList)e1.Value)[0]==name)
????????????????? {
???????????????????? flag=true;
????????????? ?????? break;
????????????????? }
????????????? }
????????????? if(flag)
????????????? {
????????????????? TimeSpan ts=System.DateTime.Now.Subtract(Convert.ToDateTime(((ArrayList)e1.Value)[1]));
????????????????? if(ts.TotalSeconds<60)
???????????????????? throw new oa.cls.MyException("對不起,你輸入的賬戶正在被使用中,如果你是這個賬戶的真正主人,請在下次登陸時及時的更改你的密碼,因為你的密碼極有可能被盜竊了!");
????????????????? else
???????????????????? h.Remove(e1.Key);???????
????????????? }
?????????? }
?????????? else
?????????? {
????????????? h=new Hashtable();
?????????? }
?????????? ArrayList al=new ArrayList();
?????????? al.Add(name);
?????????? al.Add(System.DateTime.Now);
?????????? h[Session.SessionID]=al;
?????????? if(Cache["online"]==null)
?????????? {
????????????? Context.Cache.Insert("online",h);
?????????? }else
????????????? Cache["Online"]=h;?????????
??? }
用戶注銷的時候調用上面提到LogoutCache()方法
四.?????
設置admin目錄下的的所有頁面的基類
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections;
?
?
?
?
namespace oa.cls
{
??? public class MyBasePage : System.Web.UI.Page
??? {
?
?????? /// <summary>
?????? /// 獲取本頁是否在受保護目錄,我這里整個程序在OA的虛擬目錄下,受保護的目錄是admin目錄
?????? /// </summary>
?????? protected bool IsAdminDir
?????? {
?????????? get
??? ?????? {
????????????? return Request.FilePath.IndexOf("/oa/admin")==0;
?????????? }
?????? }
?
?????? /// <summary>
?????? /// 防止session超時,如果超時就注銷身份驗證并提示和轉向到網站默認頁
?????? /// </summary>
?????? private void PreventSessionTimeout()
?????? {
?????????? if(!this.IsAdminDir) return;
?????????? if(Session["User_Name"]==null&&this.IsAdminDir)
?????????? {????????????
????????????? System.Web.Security.FormsAuthentication.SignOut();
????????????? this.Alert("登陸超時",Request.ApplicationPath)
?????????? }
?????? }
?????? /// <summary>
?????? /// 每次刷新本頁面的時候更新Cache里的登陸時間選項,在下面的OnInit方法里調用.
?????? /// </summary>
?????? private void UpdateCacheTime()
?????? {
?????????? Hashtable h=(Hashtable)Cache["online"];
?????????? if(h!=null)
?????????? {
????????????? ((ArrayList)h[Session.SessionID])[1]=DateTime.Now;
?????????? }
?????????? Cache["Online"]=h;
?????? }
?????? /// <summary>
?????? /// 在跟蹤里輸出一個HashTable的所有元素,在下面的OnInit方法里調用.以便方便的觀察緩存數據
?????? /// </summary>
?????? /// <param name="myList"></param>
?????? private void TraceValues( Hashtable myList)?
?????? {
?????????? IDictionaryEnumerator myEnumerator = myList.GetEnumerator();
?????????? int i=0;
?????????? while ( myEnumerator.MoveNext() )
?????????? {
????????????? Context.Trace.Write( "onlineSessionID"+i, myEnumerator.Key.ToString());
????????????? ArrayList al=(ArrayList)myEnumerator.Value;
????????????? Context.Trace.Write( "onlineName"+i, al[0].ToString());
????????????? Context.Trace.Write( "onlineTime"+i,al[1].ToString());
????????????? TimeSpan ts=System.DateTime.Now.Subtract(Convert.ToDateTime(al[1].ToString()));
??? ?????????? Context.Trace.Write("當前的時間和此登陸時間間隔的秒數",ts.TotalSeconds.ToString());
????????????? i++;
?????????? }
?????? }
?
?????? /// <summary>
?????? /// 彈出信息并返回到指定頁
?????? /// </summary>
?????? /// <param name="msg">彈出的消息</param>
?????? /// <param name="url">指定轉向的頁面</param>
?????? protected void Alert(string msg,string url)
?????? {
?????????? string scriptString = "<script language=JavaScript>alert(\""+msg+"\");location.href=\""+url+"\"</script>";
?????????? if(!this.IsStartupScriptRegistered("alert"))
????????????? this.RegisterStartupScript("alert", scriptString);
?????? }
?????? /// <summary>
?????? /// 為了防止常時間不刷新頁面造成會話超時,這里寫一段腳本,每隔一分鐘向本頁發送一個請求以維持會話不被超時,這里用的是xmlhttp的無刷新請求
?????? /// 這個方法也在下面的OnInit方法里調用
?????? /// </summary>
?????? protected void XmlReLoad()
?????? {?????
?????????? System.Text.StringBuilder htmlstr=new System.Text.StringBuilder();
?????????? htmlstr.Append("<SCRIPT LANGUAGE=\"JavaScript\">");
?????????? htmlstr.Append("function GetMessage(){");
?????????? htmlstr.Append("? var xh=new ActiveXObject(\"Microsoft.XMLHTTP\");");
?????????? htmlstr.Append("? xh.open(\"get\",window.location,false);");
?????????? htmlstr.Append("? xh.send();");
?????????? htmlstr.Append("? window.setTimeout(\"GetMessage()\",60000);");
?????????? htmlstr.Append("}");
?????????? htmlstr.Append("window.onload=GetMessage();");
?????????? htmlstr.Append("</SCRIPT>?????? ");
?????????? if(!this.IsStartupScriptRegistered("xmlreload"))
????????????? this.RegisterStartupScript("alert", htmlstr.ToString());
?????? }
?
?????? override protected void OnInit(EventArgs e)
?????? {
?????????? base.OnInit(e);
?????????? this.PreventSessionTimeout();
?????????? this.UpdateCacheTime();
?????????? this.XmlReLoad();
?????????? if(this.Cache["online"]!=null)
?????????? {
????????????? this.TraceValues((System.Collections.Hashtable)Cache["online"]);
?
?????????? }
?????? }
??? }
?
}
五.?????
寫一個自定義異常類
首先要在跟目錄下寫一個錯誤顯示頁面ShowErr.aspx,這個頁面根據傳遞過來的查詢字符串msg的值,在一個Label上顯示錯誤信息。
using System;
?
namespace oa.cls
{
??? /// <summary>
??? /// MyException 的摘要說明。
??? /// </summary>
??? public class MyException:ApplicationException
??? {
?
?????????? /// <summary>
?????????? /// 構造函數
?????????? /// </summary>
?????????? public MyException():base()
?????????? {
?????????? }
?????????? /// <summary>
?????????? /// 構造函數
?????????? /// </summary>
?????????? /// <param name="ErrMessage">異常消息</param>
?????????? public MyException(string Message):base(Message)
?????????? {
?????????? ??? System.Web.HttpContext.Current.Response.Redirect("~/ShowErr.aspx?msg="+Message);
?????????? }
?????????? /// <summary>
?????????? /// 構造函數
?????????? /// </summary>
?????????? /// <param name="Message">異常消息</param>
?????????? /// <param name="InnerException">引起該異常的異常類</param>
?????????? public MyException(string Message,Exception InnerException):base(Message,InnerException)
?????????? {
?????????? }
?????? }
}
六.總結
我發現在
Session
里保存的值,比如
session["name"]
是沒有任何向服務器的請求達到
1
分鐘后就會自動丟失
,
但是
session ID
是關閉同一進程的瀏覽器頁面后達
1
分鐘后才會丟失并更換的
,
因為只要你開著瀏覽器就會有
session ID,
無論是在
url
里保存還是在
cookies
里。不知道這個結論對不對,反正我在設置了
session
的
timeout
為
1
分鐘后,
session["name"]
的值已經沒有了,可是
SessionID
還是舊的,
Global.asax
里的
Session_End
里的代碼也沒有執行,而身份驗證票據也沒有丟失。我不知道這三者之間的關系是怎樣的,誰先誰后,好像在<authentication>小節可以設置一個timeout屬性,不過項目趕的緊,我沒時間研究了。
以上這些代碼比較零散,我花費了
2
天的時間才總結出來這套方案,不是很完美,但是暫時只能這樣了,不能在這方面浪費很多時間了,大家可以把上面的代碼組織到一個類里,然后把方法都修改成靜態方法方便調用。
http://www.cnblogs.com/wayne-ivan/archive/2008/01/28/1056284.html
WEB.CONFG中對FROMS驗證模式進行設置