Forms 角色驗證[轉]

一直對forms驗證中的角色很模糊,不知道怎麼搞,昨天晚上仔細看了下csdn的雜誌,心裏稍微有點底,今天早晨一上csdn,就看到思歸大人回的一篇貼,是關於asp.net中的forms驗證roles,地址是:http://www.codeproject.com/aspnet/formsroleauth.asp
汗,怎麼是E文,我的e文特差,但是不知道爲什麼這次竟然被我看懂了,模仿他的做,竟然成功!,特把過程以及我的理解寫出來,希望對和我一樣的菜鳥有點幫助,同時我的一些理解可能錯誤,希望各位老大們能夠指出,非常感謝,下面我開始邊翻譯邊按照他的做:
1,首先我們新建一個數據庫,名字叫web,添加一個表叫users,裏面有三個字段,username字段爲主鍵,username和password字段設置爲聯合索引,不知道我這樣理解對麼?請指正
CREATE
DATABASE web

CREATE TABLE users
(
username nvarchar(64) CONSTRAINT users_PK PRIMARY KEY,
password nvarchar(128),
roles nvarchar(64)
)

CREATE INDEX credentials ON users
(
username,
password
)

我們再在users表中添加兩個用戶:pwqzc  123456  Administrator,User
                              pwq    123456  User
第一個爲名字,第二個爲密碼,第三個爲用戶所具有的角色,多個角色用,逗號分開

2,創建一個登陸頁login.aspx
裏面放兩個TextBox和一個按鈕,在按鈕的單擊事件裏寫代碼:
private void btnLogin_Click(object sender, System.EventArgs e)
{
//初始化FormsAuthentication
FormsAuthentication.Initialize();
//創建個connection和command對象
            SqlConnection conn = new SqlConnection("server=(local);uid=sa;pwd=mydream54win;database=web");
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "select roles from users where username=@username and password=@password";
//添加參數以及給參數賦值
cmd.Parameters.Add("@username",SqlDbType.VarChar,64);
cmd.Parameters["@username"].Value = Username.Value;
cmd.Parameters.Add("@password",SqlDbType.VarChar,128);
cmd.Parameters["@password"].Value = Password.Value;
            //打開數據庫連接
conn.Open();
//執行命令
SqlDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
//創建一個新的驗證票FormsAuthenticationTicket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,//票版本號
Username.Value,//cookie名字
DateTime.Now,//生成cookie時間
DateTime.Now.AddMinutes(30),//cookie的有效時間
false,//是不是永久存在的cookie
reader.GetString(0));//從數據庫讀到的用戶角色數據
//把驗證票加密
string hashTicket = FormsAuthentication.Encrypt(ticket);
//設置驗證票cookie,第一個參數爲cookie的名字,第二個參數爲cookie的值也就是加密後的票
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,hashTicket);
//設置cookie的有效期是一個禮拜
cookie.Expires = DateTime.Now.AddDays(7);
//把cookie加進Response對象發生到客戶端
Response.Cookies.Add(cookie);
//得到請求的url
string requestUrl = FormsAuthentication.GetRedirectUrl(FormsAuthentication.FormsCookieName,false);
//不要使用FormsAuthentication.RedirectFromLoginPage方法,因爲這個方法會重寫cookie
//重新定向到請求的url
Response.Redirect(requestUrl);
}
else
{
    //如果不存在此用戶,則提示一些錯誤
ErrorLabel.Text = "用戶名或者密碼錯誤,請重試!";
ErrorLabel.Visible = true;
}
//關閉數據庫連接和reader
reader.Close();
conn.Close();
}


3,第三步,在應用程序的Global.asax中,找到Application_AuthenticateRequest,寫下面代碼,記的要導入using System.Security.Principal;
using System.Web.Security;這兩個名字空間,代碼如下:
protected void Application_AuthenticateRequest(Object sender,EventArgs e)
{
if(HttpContext.Current.User!=null)//如果當前的http信息中存在用戶信息
{
if(HttpContext.Current.User.Identity.IsAuthenticated)//如果當前用戶的身份已經通過了驗證
{
if(HttpContext.Current.User.Identity is FormsIdentity)
{
    //如果當前用戶身份是FormsIdentity類即窗體驗證類,此類有個屬性能夠訪問當前用戶的驗證票
FormsIdentity fi = (FormsIdentity)HttpContext.Current.User.Identity;//創建個FormsIdentity類,用他來訪問當前用戶的驗證票
                        //獲得用戶的驗證票
FormsAuthenticationTicket ticket = fi.Ticket;
//從驗證票中獲得用戶數據也就是角色數據
string userData = ticket.UserData;
//把用戶數據用,分解成角色數組
string[] roles = userData.Split(',');
//重寫當前用戶信息,就是把角色信息也加入到用戶信息中
HttpContext.Current.User = new GenericPrincipal(fi,roles);
}
}
}
}

4,第四步,修改web.config
<configuration>
<system.web>
<authentication mode="Forms">
<forms name="MYWEBAPP.ASPXAUTH"
loginUrl="login.aspx"
protection="All"
path="/"/>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
<location path="admins">
<system.web>
<authorization>
<!-- Order and case are important below -->
<allow roles="Administrator"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<location path="users">
<system.web>
<authorization>
<!-- Order and case are important below -->
<allow roles="User"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
</configuration>

5,測試,在應用程序下新建兩個目錄admins和users,分別在他們的目錄下放個default.aspx,上面隨便寫些什麼東西,把其中的一個default.aspx設置問起始頁(在vs2003環境下),如果你輸入名字pwq和密碼是不能夠進入admins目錄下的,因爲這個用戶不屬於Administrator角色!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章