asp.net對form要驗證程式

來源:互聯網
上載者:User

3、在網站裡建立Default.aspx和Login.aspx頁面
在Login.aspx頁面裡面放入Login和CreateUserWizard控制項(因為我們建立的庫中一個使用者也沒有,CreateUserWizard控制項只是用來建立測試使用者的,建好使用者後可以把這個控制項刪除)
在Default.aspx頁面中隨便放入一些內容。
當我們訪問Default.aspx時就會自動轉入Login.aspx進行驗證了。

二、自訂實現方式
採用第一種方式時會要求建立一個資料庫,很多表,可能並不符合我們自己的業務要求。可以使用以下的自訂方式
1、利用Login控制項的Authenticate事件
這個事件就是用來進行驗證的,可以通過指定true值表示驗證通過:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
//判斷使用者名稱密碼是否正確
//
e.Authenticated = true;
}2、完全拋開Login等控制項,自己寫代碼
其實Login控制項的核心主要也就是往Cookie裡面放入一些值,那麼我們可以在自己的代碼中來進行這個操作:
protected void Button1_Click(object sender, EventArgs e)
{
//判斷使用者名稱密碼是否正確
//.
FormsAuthentication.SetAuthCookie(userName, false);
if (Context.Request["ReturnUrl"] != null)
{
Response.Redirect(Context.Request["ReturnUrl"]);
}
else
{
Response.Redirect(FormsAuthentication.DefaultUrl);
}
}採用以上兩種方式就不用建立預設的資料庫了,直接使用我們的邏輯進行驗證操作

三、自訂角色提供者
以上說的都是使用者層級的驗證,在有的情況下需要根據角色來進行驗證,比如指定某個目錄或某個aspx檔案只能讓哪幾個角色的使用者訪問,根據角色來控制的話比較方便靈活。
1、在登入驗證的時候把角色資訊也儲存到Cookie中去:
protected void Button1_Click(object sender, EventArgs e)
{
//判斷使用者名稱密碼是否正確
//.

//得到使用者的角色,測試時暫時寫死
string userRoles = "Admins,testst";
FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, user, DateTime.Now, DateTime.Now.AddMinutes(30), false, userRoles, "/");
string HashTicket = FormsAuthentication.Encrypt(Ticket);

//把角色資訊儲存到Cookie中去
HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);
Response.Cookies.Add(UserCookie);

if (Context.Request["ReturnUrl"] != null)
{
Response.Redirect(Context.Request["ReturnUrl"]);
}
else
{
Response.Redirect(FormsAuthentication.DefaultUrl);
}
}把角色資訊加密成特定的格式儲存。
2、自訂角色提供者
如果要按照角色進行驗證的話,肯定要涉及到角色提供者,在預設情況下也是會去串連預設的資料庫的,我們可以自己寫一個角色提供者來實現自己的邏輯。
首先在web.config中加入配置:
Code
enabled="true"
cacheRolesInCookie="true"
cookieName=".ASPROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All" >


type="MyRoleProvider"
writeExceptionsToEventLog="false" />

這個就是指定我們的角色提供類MyRoleProvider。
這個類必須從System.Web.Security.RoleProvider繼承,只要重載實現一個方法就可以了(其他方法返回異常):
public override string[] GetRolesForUser(string username)
{
FormsIdentity Id = HttpContext.Current.User.Identity as FormsIdentity;
if (Id != null)
{
return Id.Ticket.UserData.Split(new Char[] { ',' });
}
return null;
}也就是從我們之前儲存到Cookie中的值取得使用者角色(FormsAuthentication會自動把儲存的cookie轉化成User內的值)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.