<a href="http://blog.csdn.net/pwqzc/archive/2005/08/30/467944.aspx">http://blog.csdn.net/pwqzc/archive/2005/08/30/467944.aspx</a>
一直對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">
<!-- order and case are important below -->
<allow roles="administrator"/>
<deny users="*"/>
</location>
<location path="users">
<allow roles="user"/>
</configuration>
5,測試,在應用程式下建立兩個目錄admins和users,分别在他們的目錄下放個default.aspx,上面随便寫些什麼東西,把其中的一個default.aspx設定問起始頁(在vs2003環境下),如果你輸入名字pwq和密碼是不能夠進入admins目錄下的,因為這個使用者不屬于administrator角色!
我們來看下forms身份驗證基本原理:
一 身份驗證
要采用forms身份驗證,先要在應用程式根目錄中的web.config中做相應的設
置:
<authentication mode="forms">
<forms name=".aspxauth" loginurl="login.aspx" timeout="30"
其中<authentication mode="forms"> 表示本應用程式采用forms驗證方
式。
<forms>标簽中的name表示指定要用于身份驗證的cookie。預設是.aspxauth,其實你可以用任何名字,這也就是你在本地硬碟上看到的cookie裡面的前面的幾個字.
forms的驗證過程如下:1,生成身份驗證票,2,加密身份驗證票.3,寫回用戶端,4,浏覽器重新定向.其實這一系列的動作如果我們不用roles的話都是通過formsauthentication.redirectfromloginpage方法來完成了這一系列的工作任務.但是既然我們要使用roles授權,我們就不能夠使用這個方法,而要分開來,一步步完成.
首先是建立身份驗證票,首先我們看看formsauthenticationticket類的一個構造函數:
public formsauthenticationticket(
int version, //設為1
string name, //使用者标示
datetime issuedate, //cookie 的發出時間, 設定為 datetime.now
datetime expiration, //過期時間
bool ispersistent, //是否持久性(根據需要設定,若是設定為持久性,在發出
cookie時,cookie的expires設定一定要設定)
string userdata, //這裡用上面準備好的用逗号分割的role字元串
string cookiepath // 設為”/”,這要同發出cookie的路徑一緻,因為重新整理cookie
要用這個路徑
);
最後個參數可以省略
formsauthenticationticket ticket = new formsauthenticationticket
(1,”kent”,datetime.now, datetime.now.addminutes(30), false,userroles)
然後加密:
以後的各個頁面中通過httpcontext.current.user.identity.name判斷使用者辨別,
httpcontext.current.user.isinrole("admin")判斷使用者是否屬于某一角色(或某一組)
歡迎加群互相學習,共同進步。qq群:ios: 58099570 | android: 330987132 | go:217696290 | python:336880185 | 做人要厚道,轉載請注明出處!http://www.cnblogs.com/sunshine-anycall/archive/2009/03/19/1416111.html