Forms验证中的roles

80酷酷网    80kuku.com

      一直对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>
</co

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: