.net下基于Forms的roles访问控制
?
转自:http://blog.csdn.net/is5well/archive/2008/03/11/2168473.aspx
?
今天终于有时间,搞懂了roles验证,如有地方理解错,望大家指正 !
我们先配置好web.config文件
<configuration>
??? <appSettings/>
??? <connectionStrings/>
??? <system.web>
??????? <compilation debug="false" />
????? <authentication mode="Forms" >
??????? <forms name="myljj" loginUrl="login.aspx" protection="All" path="/"></forms>?????
????? </authentication>
????? <authorization >
??????? <allow users="*"/>
????? </authorization>
??? </system.web>
? <location path="admin">
??? <system.web>
????? <authorization>
??????? <allow roles="admin"/>
??????? <deny users="*"/>
????? </authorization>
??? </system.web>
? </location>
? <location path="user">
??? <system.web>
????? <authorization>
??????? <allow? roles="user"/>
??????? <deny users="*"/>
????? </authorization>
??? </system.web>
? </location>
</configuration>
admin是我们管理员页面的目录,user是普通用户的网页目录
这里有两个角色,一个是admin,另一个是user。但要注意: <authorization>
??????? <allow roles="admin"/>
??????? <deny users="*"/>
????? </authorization>
类似这里的顺序不能乱
ok,下面我们在登录页面写下: protected void Button1_Click(object sender, EventArgs e)
??? {
??????? //用户名:ljj,ljj,admin
??????? //用户名:user,user,user
??????? //获取角色列表
??????? FormsAuthentication.Initialize();
??????? if (TextBox1.Text=="ljj"||TextBox1.Text=="user")//这里假设用户存在
??????? {
??????????? FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
??????????? (1, TextBox1.Text, DateTime.Now, DateTime.Now.AddMinutes(2), false, TextBox2.Text);
??????????? string hastick = FormsAuthentication.Encrypt(ticket);
??????????? HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hastick);
??????????? cookie.Expires = DateTime.Now.AddMinutes(20);
??????????? Response.Cookies.Add(cookie);
??????????? string url = FormsAuthentication.GetRedirectUrl(FormsAuthentication.FormsCookieName, false);
??????????? Response.Redirect(url);
??????? }
??????? else
??????? {
??????????? Response.Write("用户不存在");
??????? }
??? }
解析:TextBox1.Text 是用户名,TextBox2.Text是角色名,我这里只是方便测试用,至于具体的就从数据库中获取
我这里省略了,好的,我们现在在全局应用程序Global.asax里面写入:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
??? {
??????? if (HttpContext.Current.User != null)
??????? {
??????????? if (HttpContext.Current.User.Identity.IsAuthenticated)
??????????? {
??????????????? if (HttpContext.Current.User.Identity is FormsIdentity)
??????????????? {
??????????????????? FormsIdentity iden = (FormsIdentity)(HttpContext.Current.User.Identity);
??????????????????? FormsAuthenticationTicket ticket = iden.Ticket;
??????????????????? string userdata = ticket.UserData;
??????????????????? string[] rolues = userdata.Split(',');
??????????????????? HttpContext.Current.User = new GenericPrincipal(iden, rolues);
??????????????? }
??????????? }
??????? }
??? }
要导入空间:<%@ Import Namespace="System.Security.Principal" %>
ok,搞店,欢迎交流QQ:344716133
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/is5well/archive/2008/03/11/2168473.aspx