Asp.Net安全驗證小結
http://www.cnblogs.com/kwklover/archive/2004/06/22/17806.aspx
1,基於windows的安全驗證
web.config檔案:
<configuration>
<system.web>
<authentication mode="Windows" />
<identity impersonate="true" />
<authorization>
<allow roles="BUILTIN/groupname" users="computername/UserName,computername/UserName" />
<deny users="*" />
</authorization>
</system.web>
</configuration>
在.aspx檔案中無需任何代碼就可以實現驗證,但可以在.aspx檔案擷取登陸使用者的資訊
需匯入命名空間:System.Security.Principal
if(User.Identity.IsAuthenticated)//判斷使用者是否驗證,似乎可有可無
{
WindowsIdentity objWinIdentity=WindowsIdentity.GetCurrent();
lblHelloMsg.Text="the name:"+objWinIdentity.Name+"<br>Type:"+ objWinIdentity.AuthenticationType+"IsInRole:"+User.IsInRole("computername//groupname");
}
2,基於web.config forms驗證
web.config檔案:
<configuration>
<system.web>
<authentication mode="Forms">
<forms name="MyApp" path="/" loginUrl="login.aspx"
protection="All" timeout="30">
<credentials passwordFormat="Clear">
<user name="kwk" password="test" />
<user name="ljx" password="test" />
</credentials>
</forms>
</authentication>
<authorization>
<allow users="kwk,ljx" />
<deny users="?" />
</authorization>
</system.web>
</configuration>
login.aspx檔案:需要提供兩個文字框用於填寫使用者和密碼(txtUsr,txtPwd),一個單選框判斷是否永久儲存
還需要一個按鈕控制項則響應該button的代碼如下:
void DoLogin(Object sender, EventArgs e)
{
if(FormsAuthentication.Authenticate(txtUsr.Value,txtPwd.Value))
{
FormsAuthentication.RedirectFromLoginPage(txtUsr.Value,chkPersist.Checked);
}
else
//為代碼完整性而設定,可以不寫
{
Response.Write("authentication fails");
}
}
然後在別的頁面可以獲得登陸使用者的值:
if(User.Identity.IsAuthenticated)//可以不需要判斷
{
Response.Write("your name:"+User.Identity.Name);
Response.Write("驗證類型:"+User.Identity.AuthenticationType);//forms,windows等
}
3,基於自訂forms驗證
web.config檔案(基本上不需要什麼設定):
<system.web>
<authentication mode="Forms">
<forms name="MyApp" path="/" loginUrl="custom-login.aspx"
protection="All" timeout="30" >
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
custom-login.aspx檔案,基本原理還是跟2中說的一樣,如:
if (blnIsAuthenticated) //注意這個blnIsAuthenticated是一個自己定義的變數
//當我們把使用者輸入的資訊和資料庫(或xml)的資訊比對,存在則把該變數設為true,反之false
//這是跟2不一樣的地方
{
FormsAuthentication.RedirectFromLoginPage(txtUsr.Value, chkPersist.Checked);
//txtUsr和chkPersist分別為textbox,checkbox控制項
}
else
{
//驗證失敗提示資訊
}
剩下的如在其他頁面獲得使用者資訊,如2一樣
4,退出登陸
響應退出登陸按鈕的代碼:
FormsAuthentication.SignOut();
Response.Clear();
Response.Redirect(Request.UrlReferrer.ToString());//重新導向到前一個頁面