aps.net 基于Forms 带有角色的身份验证

     
---------------------------------------Web.Config文件配置信息 --------------------

        <authentication mode="Forms">
            <forms name="app" loginUrl="Login.aspx"></forms>
        </authentication>

    <!--拦截页面-->
    <location path="Admin">
        <system.web>
            <authorization>
                <allow roles="admin"/>
                <!--拒绝所有其他的用户访问-->
                <deny users="*"/>
            </authorization>
        </system.web>
    </location>
    <location path="BackUp">
        <system.web>
            <authorization>
               <!--admin bk 的用户角色-->
                <allow roles="admin,bk"/>
                <!--拒绝所有用户访问-->
                <deny users="*"/>
            </authorization>
        </system.web>
    </location>
    <location path="User">
        <system.web>
            <authorization>
                <!--拒绝所有匿名用户访问-->
                <deny users="?"/>
            </authorization>
        </system.web>
    </location>


---------------------------------这是在Global.asax 文件代码-----------------------------
  protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.User != null)
            {
                // 判断用户是否进行了身份验证
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    // 判断用户的是否进行了Forms 身份验证
                    if (HttpContext.Current.User.Identity is FormsIdentity)
                    {
                        // 获得用户进行了Forms 身份验证的身份标识
                        FormsIdentity userIdent = (FormsIdentity)HttpContext.Current.User.Identity;
                        // 从身份验证票中获得用户数据
                        string userData = userIdent.Ticket.UserData;
                        //分割用户信息得到用户角色数据信息
                        string[] roles = userData.Split(',');
                        //从用户标识和角色数组初始化GenericPrincipal
                        HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(userIdent, roles);

                    }
                }
            }
        }

-----------------------------------------------登录页面设置-------------------------------

                FormsAuthenticationTicket tickect = new FormsAuthenticationTicket(1, "XXOO", DateTime.Now,                 

DateTime.Now.AddMinutes(5), false, role);

                //加密票据
                string Encrypt = FormsAuthentication.Encrypt(tickect);

                //创建Cookies
                HttpCookie mycookies = new HttpCookie(FormsAuthentication.FormsCookieName,Encrypt);
                //将cookies 写入客户端
                Response.Cookies.Add(mycookies);

                //跳转到初始请求页  或默认页
                Response.Redirect(FormsAuthentication.GetRedirectUrl("XXOO",false));

原文地址:https://www.cnblogs.com/voidobject/p/3975501.html