ASP.NET 中的表單身份驗證(Forms Authentication)
表單驗證可以通使用一個登入頁面驗證使用者的使用者名稱和密碼。未通過驗證的請求會被重定向到登入頁面,要求使用者輸入其憑據資訊(同常是使用者名稱和密碼)。如果請求通過驗證,系統將簽發一個身份驗證票據,在使用者會話期間,這個票據維護使用者的身份標識資訊以及使用者角色。通過FormsAuthentication 類可以訪問使用者的標識資訊和角色。
下面實現一個簡單的Forms Authentication:
(1)新建一個新的Web應用程式,建立一個登入頁面。
(2)修改應用程式根目錄下的web.config檔案,設定應用程式的驗證模式為表單驗證。
<system.web> <authentication mode="Forms"> <forms loginUrl="Logon.aspx" name=".ASPXFORMSAUTH"></forms> </authentication> </system.web>
(3)在限制訪問的目錄下建立一個web.config檔案,修改authorization配置節阻止匿名使用者的訪問。
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
(4)在登入面頁中鑑別使用者並且建立一個表單驗證票據。
下面的程式碼假定你有一個IsAuthenticated函式用於驗證使用者,一個GetRoles函式用於獲取使用者角色。
void OnLogin(object sender, EventArgs e)
{
if(IsAuthenticated(username, password))
{
string roles = GetRoles(username);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // 版本
DateTime.Now, // 票據的簽發時間
DateTime.Now.AddHours(1), // 票據的過期時間
false, // 是否為永久Cookie
roles // 附加的使用者資料,此處用來存放使用者角色
);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(username, false));
}
}
(5)捕獲驗證請求事件,建立一個GenericPrinciple物件。
void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
string[] roles = ticket.UserData.Split(new char[] { ',' });
FormsIdentity identity = new FormsIdentity(ticket);
GenericPrincipal priciple = new GenericPrincipal(identity, roles);
Context.User = priciple;
}