步驟一:
在根目錄下的web.config中加入:
<system.web>
<authentication mode="Forms">
<forms loginUrl="Login.aspx" defaultUrl="admin/admin.aspx" name=".ASPXFORMSAUTH">
</forms>
</authentication>
</system.web>
loginUrl:使用者沒有登入,跳轉到的登入頁面
defaultUrl:正確登入之後,在沒有指向頁的時候,弄人跳轉的頁面
步驟二:
在admin檔案夾下建立一個web.config檔案,並加入以下代碼
<system.web>
<!--拒絕匿名使用者存取此目錄下的任何檔案-->
<authorization>
<deny users="?"/>
</authorization>
</system.web>
deny users="?":表示禁止匿名使用者存取admin目錄下的任何檔案
到目前為止,只要你訪問admin下的任何檔案,都會自動跳轉到Login.aspx登陸頁面了,要求你先登入,否則別想看到頁面。
步驟三:
在根目錄下,建立Login.aspx登陸頁面(可不是在admin目錄下哦),加兩個textbox控制項和一個botton控制項,分別是使用者名稱,密碼,和登陸按鈕
雙擊登陸按鈕,在其登陸方法裡寫上:
protected void btn_Login_Click(object sender, EventArgs e)
{
if (TextBox1.Text == "admin" && TextBox2.Text == "fenghua17173")
{
//“通知”表單驗證,該使用者名稱已經通過身分識別驗證
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, true);
}
else
{
Response.Write("<script>alert('帳號或密碼有誤,登入失敗!');</script>");
}
}
ok,這時你在login.aspx頁面裡填上帳號密碼,系統就會根據根你在根目錄下web.config中配置的defaultUrl地址路徑跳轉過去,也就是admin/admin.aspx頁面。
現在admin目錄下的所有頁面,均已通過身分識別驗證,得到了可訪問的票據。
也可以使用:
string user = "a";
System.Web.Security.FormsAuthenticationTicket tk = new System.Web.Security.FormsAuthenticationTicket(1,
user,
DateTime.Now,
DateTime.Now.AddMinutes(3000000),
true,
"",
System.Web.Security.FormsAuthentication.FormsCookiePath
);
string key = System.Web.Security.FormsAuthentication.Encrypt(tk); //得到加密後的身分識別驗證票字串
HttpCookie ck = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, key);
HttpContext.Current.Response.Cookies.Add(ck);
Response.Redirect("default.aspx");
最後一點:
有登陸,當然別忘了登出,這個更簡單:
在admin目錄下的任何一個頁面中,加一個登出button按鈕,並在其方法下寫入:
//退出系統,登出使用者
protected void btn_Logout_Click(object sender, EventArgs e)
{
//刪除使用者票據
FormsAuthentication.SignOut();
//重新定向到登陸頁面
FormsAuthentication.RedirectToLoginPage();
}
備忘:
<authentication mode="Forms">
<forms loginUrl="Login.aspx"
protection="All"
timeout="30"
name="AppNameCookie"
path="/FormsAuth"
requireSSL="false"
slidingExpiration="true"
defaultUrl="default.aspx"
cookieless="UseCookies"
enableCrossAppRedirects="false"/>
</authentication>
· loginUrl 指向登入頁面,你需要把它放在支援SSL的目錄下
· Protection 設定成"All"表示為認證憑據同時啟用資料來源驗證和加密
· Timeout 指定了認證的存留時間
· name and path are set to unique values for the current application.
· requireSSL 設定成"false"表示關閉cookie的SSL加密
· slidingExpiration 如果設定成"true"的話,每次訪問到期時間將會重設
· defaultUrl 就是設定程式的首頁
· cookieless 設定成"UseCookies"表示使用cookie來傳遞認證票據
· enableCrossAppRedirects 設定成"false"表示程式不接受外部的請求