FormsAuthenticationTicket 基于Forms 验证
以前看到过FormsAuthenticationTicket 验证 没去了解过 . 今天动手实践了下下面是小demo的步骤
目录机构
2.在Default.aspx.cs里的代码 页面就三个控件 两个文本框 一个复选框
3. 在admin/OK.ASPX .cs load事件里
if (User.IsInRole("admin") )//cookie 标示 { Response.Write(User.Identity.Name.ToString());//输出获取存入的身份验证数据 } else { Response.Write("错误"); }
然后再添加一个Global.asax 文件
代码如下
HttpApplication app = (HttpApplication)sender; HttpContext ctx = app.Context; //获取本次Http请求的HttpContext对象 if (ctx.User != null) { if (ctx.Request.IsAuthenticated == true) //验证过的一般用户才能进行角色验证 { System.Web.Security.FormsIdentity fi = (System.Web.Security.FormsIdentity)ctx.User.Identity; System.Web.Security.FormsAuthenticationTicket ticket = fi.Ticket; //取得身份验证票 string userData = ticket.UserData;//从UserData中恢复role信息 string[] roles = userData.Split(','); //将角色数据转成字符串数组,得到相关的角色信息 ctx.User = new System.Security.Principal.GenericPrincipal(fi, roles); //这样当前用户就拥有角色信息了 } }
最后配置webconfig
<?xml version="1.0"?> <!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <system.web> <authentication mode="Forms"> <forms name=".FormsAuth" loginUrl="default.aspx" protection="All" path="admin"/> </authentication> <authorization> <allow users="admin"/>//允许凭证为admin 访问 <deny users="?"/> </authorization> <compilation debug="true" targetFramework="4.0"/> </system.web> </configuration>
---恢复内容结束---