62,267
社区成员
发帖
与我相关
我的任务
分享string userName = "zhang";
string userRole = "admin";
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
userName,
DateTime.Now,
DateTime.Now.AddMinutes(30),
false,
userRole,
"/");
string hashTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
Response.Cookies.Add(cookie);HttpApplication App = (HttpApplication)sender;
HttpContext Ctx = App.Context; //获取本次Http请求相关的HttpContext对象
if (Ctx.Request.IsAuthenticated == true) //验证过的用户才进行role的处理
{
FormsIdentity Id = (FormsIdentity)Ctx.User.Identity;
FormsAuthenticationTicket Ticket = Id.Ticket; //取得身份验证票
string[] Roles = Ticket.UserData.Split(','); //将身份验证票中的role数据转成字符串数组
Ctx.User = new GenericPrincipal(Id, Roles); //将原有的Identity加上角色信息新建一个GenericPrincipal表示当前用户,这样当前用户就拥有了role信息
}<authentication mode="Forms" >
<forms name="DemoAuth" loginUrl="Web/login.aspx" timeout="30" path="/" />
</authentication>
<authorization>
<deny users="?"/>
</authorization>
<location path="Demo1">
<system.web>
<authorization>
<allow roles="admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>//在这里roleOk已经是true了,为什么还是跳不进去,郁闷!待解!急!
bool roleOk = HttpContext.Current.User.IsInRole("admin");
Response.Redirect("Demo1/demo1.aspx");