天天看点

[转]Forms验证中的roles

<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

&lt;configuration&gt;

&lt;system.web&gt;

&lt;authentication mode="forms"&gt;

&lt;forms name="mywebapp.aspxauth"

loginurl="login.aspx"

protection="all"

path="/"/&gt;

&lt;/authentication&gt;

&lt;authorization&gt;

&lt;allow users="*"/&gt;

&lt;/authorization&gt;

&lt;/system.web&gt;

&lt;location path="admins"&gt;

&lt;!-- order and case are important below --&gt;

&lt;allow roles="administrator"/&gt;

&lt;deny users="*"/&gt;

&lt;/location&gt;

&lt;location path="users"&gt;

&lt;allow roles="user"/&gt;

&lt;/configuration&gt;

5,测试,在应用程序下新建两个目录admins和users,分别在他们的目录下放个default.aspx,上面随便写些什么东西,把其中的一个default.aspx设置问起始页(在vs2003环境下),如果你输入名字pwq和密码是不能够进入admins目录下的,因为这个用户不属于administrator角色!

 我们来看下forms身份验证基本原理:

一 身份验证

要采用forms身份验证,先要在应用程序根目录中的web.config中做相应的设

置:

&lt;authentication mode="forms"&gt; 

    &lt;forms name=".aspxauth" loginurl="login.aspx" timeout="30" 

其中&lt;authentication mode="forms"&gt; 表示本应用程序采用forms验证方

式。

&lt;forms&gt;标签中的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

继续阅读