我给page1.aspx页面加了角色控制,只有角色为“admin”的用户才可以浏览,问题是即使角色不是“admin”的用户照样可以浏览paage1.aspx.现贴出代码。web.config里的配置<location path="page1.aspx">
<system.web>
<authorization>
<allow roles= "admin"/>
<deny users= "?"/>
</authorization>
</system.web>
</location>用户验证时的代码 string userRoles = "guest";
FormsAuthenticationTicket Ticket
= new FormsAuthenticationTicket(1, "user1", DateTime.Now, DateTime.Now.AddMinutes(1), true, userRoles, "/"); //建立身份验证票对象
string HashTicket = FormsAuthentication.Encrypt(Ticket);
HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);
//生成Cookie
Context.Response.Cookies.Add(UserCookie);
Context.Response.Redirect(Context.Request["ReturnUrl"]); // 重定向到用户申请的初始页面
Global.asax文件里的代码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 System.Security.Principal.GenericPrincipal(Id, Roles); //将原有的Identity加上角色信息新建一个GenericPrincipal表示当前用户,这样当前用户就拥有了role信息
}
<system.web>
<authorization>
<allow roles= "admin"/>
<deny users= "?"/>
</authorization>
</system.web>
</location>用户验证时的代码 string userRoles = "guest";
FormsAuthenticationTicket Ticket
= new FormsAuthenticationTicket(1, "user1", DateTime.Now, DateTime.Now.AddMinutes(1), true, userRoles, "/"); //建立身份验证票对象
string HashTicket = FormsAuthentication.Encrypt(Ticket);
HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);
//生成Cookie
Context.Response.Cookies.Add(UserCookie);
Context.Response.Redirect(Context.Request["ReturnUrl"]); // 重定向到用户申请的初始页面
Global.asax文件里的代码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 System.Security.Principal.GenericPrincipal(Id, Roles); //将原有的Identity加上角色信息新建一个GenericPrincipal表示当前用户,这样当前用户就拥有了role信息
}
<allow roles= "admin"/>
<deny users= "?"/>
顺序调过来
<deny users= "?"/>
<allow roles= "admin"/>
试试看