加入收藏 | 设为首页 | 会员中心 | 我要投稿 核心网 (https://www.hxwgxz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程 > 正文

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

发布时间:2021-07-20 19:33:43 所属栏目:编程 来源:互联网
导读:Forms身份验证用来判断是否合法用户,当用户合法后,再通过用户的角色决定能访问的页面。


        //改造原来的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页面加载代码如下:

复制代码 代码如下:

(编辑:核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读