转,FormsAuthenticationTicket 的使用

DataRow dr = dt.Rows[0];
                //获取用户职位作为权限
                System.Web.Security.FormsAuthenticationTicket Ticket = 
                    new System.Web.Security.FormsAuthenticationTicket
                    (1, dr["UserName"].ToString(), DateTime.Now, DateTime.Now.AddHours(24), 
                    true, dr["Userposition"].ToString()); //建立身份验证票对象 
                string HashTicket = System.Web.Security.FormsAuthentication.Encrypt(Ticket); //加密序列化验证票为字符串 
                HttpCookie UserCookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, HashTicket); //生成Cookie 
                Context.Response.Cookies.Add(UserCookie); //输出Cookie


<location path="system/otherdepartment.aspx">
    <!--非行政列表不允许职员查看-->
   <system.web>
    <authorization>
        <allow roles="3"/>
     <allow roles="2"/>
        <allow roles="1"/>
     <deny users="*"/>
    </authorization>
   </system.web>
</location>

=========

Global.asax

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        /*HttpApplication HApp = (HttpApplication)sender;
        HttpContext HCtx = HApp.Context; //获取本次Http请求的HttpContext对象 
        if (HCtx.Request.IsAuthenticated == true) //验证过的一般用户才能进行角色验证 
        {
            System.Web.Security.FormsIdentity Id = (System.Web.Security.FormsIdentity)HCtx.User.Identity;
            System.Web.Security.FormsAuthenticationTicket Ticket = Id.Ticket; //取得身份验证票 
            string[] Roles = Ticket.UserData.Split(','); //将角色数据转成字符串数组,得到相关的角色信息 
            HCtx.User = new System.Security.Principal.GenericPrincipal(Id, Roles); //这样当前用户就拥有了角色信息了 
        }*/
        if (Context.Request.IsAuthenticated)
        {
            HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);//解密 
            string[] roles = authTicket.UserData.Split(new char[] { ';' });//根据存入时的格式分解,;或|.... 
            Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);//存到HttpContext.User中 
            //HttpContext.Current.User.IsInRole(roles);//判断某个角色验证 
        }

  

posted @ 2011-11-04 16:08  flb  阅读(784)  评论(0)    收藏  举报