asp.net Forms身份验证和基于角色的权限访问(3)


        //改造原来的User,给其添加一个用户所属的角色数据
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.User != null )
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    if (HttpContext.Current.User.Identity is FormsIdentity)
                    {
                        FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                        FormsAuthenticationTicket ticket = id.Ticket;

                        string userData = ticket.UserData;
                        string[] roles = userData.Split(',');
                        //重建HttpContext.Current.User,加入用户拥有的角色数组
                        HttpContext.Current.User = new GenericPrincipal(id, roles);
                    }
                }
            }
        }


    5、在Admin目录中Manager.aspx页面加载代码如下:

复制代码 代码如下:


        protected void Page_Load(object sender, EventArgs e)
        {
            //判断通过身份验证的用户是否有权限访问本页面
            FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
            //判断通过身份验证的用户是否是Admin角色
            if (!id.Ticket.UserData.Contains("Admin"))
            {
                //跳转到访问权限不够的错误提示页面
                Response.Redirect("~/Error/AccessError.htm", true);
            }
        }
        //安全退出按钮的代码
        protected void btnExit_Click(object sender, EventArgs e)
        {
            //注销票据
            FormsAuthentication.SignOut();
            ClientScriptManager csm = this.Page.ClientScript;
            csm.RegisterStartupScript(this.GetType(), "exit_tip", "alert('您已经安全退出了!');", true);
        }


    6、在Users目录中Welcome.aspx页面加载代码如下:

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjfywz.html