Forms验证之多角色代码

      前几天在做一个网站,想实现这样的一个功能:根据不同角色实现对多个登陆页面的重定向,在网上参考了些资料,整理下,全部记录下来,仅供参考。。。。。

web.config<?xml version="1.0"?>
<configuration>
    <configSections>
        <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
            <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
                <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" />
                <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
                    <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere" />
                    <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" />
                    <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" />
                </sectionGroup>
            </sectionGroup>
        </sectionGroup>
    </configSections>
    <connectionStrings>
        <add name="connectionString" connectionString="Data Source=yqkc.cn;Initial Catalog=Yqke_Search;User ID =yqkc;Pwd=1qaz2wsx" providerName="System.Data.SqlClient"/>
    </connectionStrings>
    <system.web>
        <pages>
            <controls>
                <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
            </controls>
        </pages>

        <compilation debug="true">
            <assemblies>
                <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
                <add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
                <add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
            </assemblies>
        </compilation>
        <httpHandlers>
            <remove verb="*" path="*.asmx" />
            <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
            <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
            <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false" />
            <add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro.2" />
        </httpHandlers>
        <httpModules>
            <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

        </httpModules>
        <authentication mode="Forms">
            <forms name="adminCookies" defaultUrl="Default.aspx" loginUrl="Login.aspx" protection="All" path="/"/>
        </authentication>
        <authorization>
            <allow users="*"/>
        </authorization>
    </system.web>

    <location path="Views/Admin">
        <system.web>
            <authorization>
                <allow roles="Admins"/>
                <deny users="*"/>
            </authorization>
        </system.web>
    </location>
    <location path="Views/Admin/Login.aspx">
        <system.web>
            <authorization>
                <allow users="*"/>
            </authorization>
        </system.web>
    </location>
    <location path="Views/User">
        <system.web>
            <authorization>
                <deny users="?"/>
            </authorization>
        </system.web>
    </location>

    <system.web.extensions>
        <scripting>
            <webServices>
                <!-- Uncomment this line to customize maxJsonLength and add a custom converter -->
                <!--
      <jsonSerialization maxJsonLength="500">
        <converters>
          <add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>
        </converters>
      </jsonSerialization>
      -->
                <!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. -->
                <!--
        <authenticationService enabled="true" requireSSL = "true|false"/>
      -->
                <!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved
           and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and
           writeAccessProperties attributes. -->
                <!--
      <profileService enabled="true"
                      readAccessProperties="propertyname1,propertyname2"
                      writeAccessProperties="propertyname1,propertyname2" />
      -->
            </webServices>
            <!--
      <scriptResourceHandler enableCompression="true" enableCaching="true" />
      -->
        </scripting>
    </system.web.extensions>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <modules>
            <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        </modules>
        <handlers>
            <remove name="WebServiceHandlerFactory-Integrated" />
            <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
            <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
            <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
            <add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro.2" />
        </handlers>
    </system.webServer>
</configuration>

Global.asax//在默认创建的Global.asax中添加此方法即可
void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        HttpApplication app = (HttpApplication)sender;

        //获取身份验证的cookie
        HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];

        if (cookie != null)
        {
            string encryptedTicket = cookie.Value;

            //解密cookie中的票据信息
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(encryptedTicket);

            //获取用户角色信息
            string[] roles = new string[] { ticket.UserData.ToString() };

            //创建用户标识
            FormsIdentity identity = new FormsIdentity(ticket);

            //创建用户的主体信息
            System.Security.Principal.GenericPrincipal user = new System.Security.Principal.GenericPrincipal(identity, roles);
            app.Context.User = user;
        }
    }

根目录下Login.aspx//根目录下添加Login.aspx
 protected void Page_Load(object sender, EventArgs e)
    {
        string ParamName = "ReturnUrl";
        string ReturnUrl = Request.QueryString[ParamName];
        if (ReturnUrl != null)
        {
            if (ReturnUrl.ToLower().IndexOf("views/admin") >= 0)
            {
                Response.Redirect("Views/Admin/Login.aspx");
            }
            else if (ReturnUrl.ToLower().IndexOf("views/user") >= 0)
            {
                Response.Redirect("Views/Account/Login.aspx");
            }
        }
        else
        {
            Response.Redirect("Default.aspx");
        }  
    }
Admin目录下Login.aspxpublic partial class Views_Account_Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.User.Identity.IsAuthenticated && Page.User.IsInRole("Admins"))
        {
            Response.Redirect("AdminMain.aspx?admin=" + username.Value);
            return;
        }
        if (!IsPostBack)
        {
            Utility.Setting(scriptHtml, keywords, description);
        }
    }
    //管理员登陆
    protected void submit_Click(object sender, ImageClickEventArgs e)
    {
        SE.Models.TbAdminLogin _TbAdminLogin = SE.DAL.TbAdminLoginService.AdminLogin(username.Value);
        if (_TbAdminLogin.Admin_Pwd.Equals(FormsAuthentication.HashPasswordForStoringInConfigFile(password.Value, "SHA1")))
        {
            double timeout = 30;
            if (savelogin.Checked)
                timeout = 1440;
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, _TbAdminLogin.Admin_Name, DateTime.Now, DateTime.Now.AddMinutes(timeout), false, "Admins", "/"); //建立身份验证票对象
            string encryptedTicket = FormsAuthentication.Encrypt(ticket);//加密序列化验证票为字符串
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);//生成Cookie
            Session["admin"] = _TbAdminLogin;
            Response.Cookies.Add(cookie);//输出Cookie
            Response.Redirect("AdminMain.aspx?admin=" + _TbAdminLogin.Admin_Name + "&logintime=" + _TbAdminLogin.Admin_LastLoginDateTime);
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<SCRIPT>alert('登陆失败!')</SCRIPT>");
        }
    }
}

用户Login.aspxpublic partial class Views_Account_Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Utility.Setting(scriptHtml, keywords, description);
            if (Page.User.Identity.IsAuthenticated)
            {
                Session["userId"] = Page.User.Identity.Name;
                Response.Redirect("../User/UserMain.aspx?user=" + username.Value);
                return;
            }
        }
    }

    //用户登陆
    protected void submit_Click(object sender, ImageClickEventArgs e)
    {
        SE.Models.TbUser _TbUser = SE.DAL.TbUserService.UserLogin(username.Value);
        if (_TbUser != null && _TbUser.User_Pwd.Equals(FormsAuthentication.HashPasswordForStoringInConfigFile(password.Value, "SHA1")))
        {
            int timeout = 30;
            if (savelogin.Checked)
                timeout = 1440;
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(_TbUser.User_Id.ToString(), false, timeout);
            string encryptedTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            Response.Cookies.Add(cookie);
            Session["user"] = _TbUser;
            Response.Redirect("../User/UserMain.aspx?user=" + _TbUser.User_Name + "&logintime=" + _TbUser.User_LastLoginDateTime);
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<SCRIPT>alert('登陆失败!')</SCRIPT>");
        }
    }
}

原文地址:https://www.cnblogs.com/myssh/p/1559809.html