<authentication mode="Forms">
      <forms name="ASPNET" defaultUrl="Default.aspx" loginUrl="Login.aspx" path="/" protection="All" timeout="120"></forms>
    </authentication>
    <authorization>
      <allow roles="admin"/>
      <deny users="*"/>
    </authorization>Login.aspx FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username,  DateTime.Now,DateTime.Now.AddMinutes(2), true, "admin",FormsAuthentication.FormsCookiePath);
 string encrpt = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrpt);
 Response.Cookies.Add(cookie);
 FormsAuthentication.RedirectFromLoginPage(username, false);
 HttpApplication app = (HttpApplication)sender;
 HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
 if (cookie != null)
   {
      string encryptedTicket = cookie.Value;
      FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(encryptedTicket);
      string[] roles = ticket.UserData.Split(',');
      FormsIdentity identity = new FormsIdentity(ticket);
      GenericPrincipal user = new GenericPrincipal(identity, roles);
      app.Context.User = user;
    }
遇到的问题:在global中Application_AuthenticateRequest中设置断点获取roles总是为空。
可以获取到加密的身份验证票信息。cookie也可以获取到。

解决方案 »

  1.   

    看看建立身份验证票对象的时候roles有没有问题..
      

  2.   

         HttpContext Ctx = App.Context ; //获取本次Http请求相关的HttpContext对象
       if (Ctx.Request.IsAuthenticated == true) //验证过的用户才进行role的处理
       {
        }
      

  3.   

    FormsIdentity Id = (FormsIdentity)Ctx.User.Identity ; Ctx.User = new GenericPrincipal (Id, Roles) ; //将原有的Identity加上角色信息新建一个GenericPrincipal表示当前用户,这样当前用户就拥有了role信息