Forms验证的知识

来源:互联网 发布:手机探鱼器软件 编辑:程序博客网 时间:2024/05/19 11:50

创建一个工程,工程中有一个Admin目录,该目录仅仅允许角色为Admin的用户或者用户名称为Admin的人员进入该目录去浏览其中的数据。

首先配置给项目的根目录的Web.Config文件如下,注意其他地方都可以采用默认的方式,仅仅在如下的部分进行修改

    <authentication mode="Forms">

    <forms name="authName" loginUrl="WebForm1.aspx" protection="All" timeout="20" path="/"/>

    </authentication>

 

     <!--  授权

           此节设置应用程序的授权策略。可以允许或拒绝不同的用户或角色访问

          应用程序资源。通配符: "*" 表示任何人,"?" 表示匿名

          (未经身份验证的)用户。

    -->

 

Admin目录下编写一个Web.Config文件如下:

<?xml version="1.0" encoding="utf-8" ?>

<configuration>   

  <system.web>

    <authorization>

        <allow roles="custom"/>

        <deny roles="Admin"/>               

        <deny users="*"/>

    </authorization>  

 </system.web>

</configuration>

 

上面的文件,仅仅当角色为custom的用户才可以进入访问该文件夹下的文件。

 

 

首先在根目录下编写一个文件WebForm1.aspx,在其上面放置一个用户名称和密码的文本框和一个按钮。编写按钮的事件。如下:

 

     //首先生成一个窗体授权的票据

              System.Web.Security.FormsAuthenticationTicket formsTicket=new System.Web.Security.FormsAuthenticationTicket(

                   1,

                   TextBox1.Text,

                   DateTime.Now,

                   DateTime.Now.AddDays(2),

                   false,

                   "Admin");

              //加密窗体授权的票据

              string encTicket=System.Web.Security.FormsAuthentication.Encrypt(formsTicket);

              //利用生成的加密的票据来生成HttpCookie

              HttpCookie authCookie=new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName,encTicket);

              Response.Cookies.Add(authCookie);

              Response.Redirect("Admin/WebForm2.aspx");

 

 

然后在global.asax文件中填写如下的事件响应

         protected void Application_AuthenticateRequest(Object sender, EventArgs e)

         {

 

              //首先获取WebConfig文件中的配置

              string configCookie=System.Web.Security.FormsAuthentication.FormsCookieName;

              HttpCookie authCookie=Context.Request.Cookies[configCookie];

              if(authCookie==null)

                   return;

              System.Web.Security.FormsAuthenticationTicket authTicket=null;

              //由于前面已经利用票据加密生成了Cookie,现在取出来进行解密

              authTicket=System.Web.Security.FormsAuthentication.Decrypt(authCookie.Value);

              if(null==authTicket)

                   return;

 

              //由于验证票据的UserData中存放的是用户的角色信息,来存取角色信息

              string []roles=authTicket.UserData.Split(new char[]{','});

 

              //利用获取的票据来获取ID

              System.Web.Security.FormsIdentity id=new System.Web.Security.FormsIdentity(authTicket);

              //生成具有验证票信息和角色信息

              System.Security.Principal.GenericPrincipal principal=new System.Security.Principal.GenericPrincipal(id,roles);

              Context.User=principal;

         }

作了如上的代码就可以实现了