Form表单身份验证例子

http://topic.csdn.net/t/20050830/10/4239405.html(转)

步骤:

一直对forms验证中的角色很模糊,不知道怎么搞,昨天晚上仔细看了下csdn的杂志,心里稍微有点底,今天早晨一上csdn,就看到思归大人回的一篇贴,是关于asp.net中的forms验证roles,地址是:http://www.codeproject.com/aspnet/formsroleauth.asp  
  汗,怎么是E文,我的e文特差,但是不知道为什么这次竟然被我看懂了,模仿他的做,竟然成功!,特把过程以及我的理解写出来,希望对和我一样的菜鸟有点帮助,同时我的一些理解可能错误,希望各位老大们能够指出,非常感谢,下面我开始边翻译边按照他的做:  
  1,首先我们新建一个数据库,名字叫web,添加一个表叫users,里面有三个字段,username字段为主键,username和password字段设置为联合索引,不知道我这样理解对么?请指正  
  CREATE    
  DATABASE   web  
   
  CREATE   TABLE   users  
  (  
  username   nvarchar(64)   CONSTRAINT   users_PK   PRIMARY   KEY,  
  password   nvarchar(128),  
  roles   nvarchar(64)  
  )  
   
  CREATE   INDEX   credentials   ON   users  
  (  
  username,  
  password  
  )  
   
  我们再在users表中添加两个用户:pwqzc     123456     Administrator,User  
                                                              pwq         123456     User  
  第一个为名字,第二个为密码,第三个为用户所具有的角色,多个角色用,逗号分开  
   
  2,创建一个登陆页login.aspx  
  里面放两个TextBox和一个按钮,在按钮的单击事件里写代码:  
  private   void   btnLogin_Click(object   sender,   System.EventArgs   e)  
  {  
  //初始化FormsAuthentication  
  FormsAuthentication.Initialize();  
  //创建个connection和command对象  
                          SqlConnection   conn   =   new   SqlConnection("server=(local);uid=sa;pwd=mydream54win;database=web");  
  SqlCommand   cmd   =   conn.CreateCommand();  
  cmd.CommandText   =   "select   roles   from   users   where   username=@username   and   password=@password";  
  //添加参数以及给参数赋值  
  cmd.Parameters.Add("@username",SqlDbType.VarChar,64);  
  cmd.Parameters["@username"].Value   =   Username.Value;  
  cmd.Parameters.Add("@password",SqlDbType.VarChar,128);  
  cmd.Parameters["@password"].Value   =   Password.Value;  
                          //打开数据库连接  
  conn.Open();  
  //执行命令  
  SqlDataReader   reader   =   cmd.ExecuteReader();  
  if(reader.Read())  
  {  
  //创建一个新的验证票FormsAuthenticationTicket  
  FormsAuthenticationTicket   ticket   =   new   FormsAuthenticationTicket(  
  1,//票版本号  
  Username.Value,//cookie名字  
  DateTime.Now,//生成cookie时间  
  DateTime.Now.AddMinutes(30),//cookie的有效时间  
  false,//是不是永久存在的cookie  
  reader.GetString(0));//从数据库读到的用户角色数据  
  //把验证票加密  
  string   hashTicket   =   FormsAuthentication.Encrypt(ticket);  
  //设置验证票cookie,第一个参数为cookie的名字,第二个参数为cookie的值也就是加密后的票  
  HttpCookie   cookie   =   new   HttpCookie(FormsAuthentication.FormsCookieName,hashTicket);  
  //设置cookie的有效期是一个礼拜  
  cookie.Expires   =   DateTime.Now.AddDays(7);  
  //把cookie加进Response对象发生到客户端  
  Response.Cookies.Add(cookie);  
  //得到请求的url  
  string   requestUrl   =   FormsAuthentication.GetRedirectUrl(FormsAuthentication.FormsCookieName,false);  
  //不要使用FormsAuthentication.RedirectFromLoginPage方法,因为这个方法会重写cookie  
  //重新定向到请求的url  
  Response.Redirect(requestUrl);  
  }  
  else  
  {  
          //如果不存在此用户,则提示一些错误  
  ErrorLabel.Text   =   "用户名或者密码错误,请重试!";  
  ErrorLabel.Visible   =   true;  
  }  
  //关闭数据库连接和reader  
  reader.Close();  
  conn.Close();  
  }  
   
   
  3,第三步,在应用程序的Global.asax中,找到Application_AuthenticateRequest,写下面代码,记的要导入using   System.Security.Principal;  
  using   System.Web.Security;这两个名字空间,代码如下:  
  protected   void   Application_AuthenticateRequest(Object   sender,EventArgs   e)  
  {  
  if(HttpContext.Current.User!=null)//如果当前的http信息中存在用户信息  
  {  
  if(HttpContext.Current.User.Identity.IsAuthenticated)//如果当前用户的身份已经通过了验证  
  {  
  if(HttpContext.Current.User.Identity   is   FormsIdentity)  
  {  
          //如果当前用户身份是FormsIdentity类即窗体验证类,此类有个属性能够访问当前用户的验证票  
  FormsIdentity   fi   =   (FormsIdentity)HttpContext.Current.User.Identity;//创建个FormsIdentity类,用他来访问当前用户的验证票  
                                                  //获得用户的验证票  
  FormsAuthenticationTicket   ticket   =   fi.Ticket;  
  //从验证票中获得用户数据也就是角色数据  
  string   userData   =   ticket.UserData;  
  //把用户数据用,分解成角色数组  
  string[]   roles   =   userData.Split(',');  
  //重写当前用户信息,就是把角色信息也加入到用户信息中  
  HttpContext.Current.User   =   new   GenericPrincipal(fi,roles);  
  }  
  }  
  }  
  }  
   
  4,第四步,修改web.config  
  <configuration>  
  <system.web>  
  <authentication   mode="Forms">  
  <forms   name="MYWEBAPP.ASPXAUTH"  
  loginUrl="login.aspx"  
  protection="All"  
  path="/"/>  
  </authentication>  
  <authorization>  
  <allow   users="*"/>  
  </authorization>  
  </system.web>  
  <location   path="admins">  
  <system.web>  
  <authorization>  
  <!--   Order   and   case   are   important   below   -->  
  <allow   roles="Administrator"/>  
  <deny   users="*"/>  
  </authorization>  
  </system.web>  
  </location>  
  <location   path="users">  
  <system.web>  
  <authorization>  
  <!--   Order   and   case   are   important   below   -->  
  <allow   roles="User"/>  
  <deny   users="*"/>  
  </authorization>  
  </system.web>  
  </location>  
  </configuration>  
   
  5,测试,在应用程序下新建两个目录admins和users,分别在他们的目录下放个default.aspx,上面随便写些什么东西,把其中的一个default.aspx设置问起始页(在vs2003环境下),如果你输入名字pwq和密码是不能够进入admins目录下的,因为这个用户不属于Administrator角色!  

 //初始化FormsAuthentication  
        FormsAuthentication.Initialize();
        //创建个connection和command对象  
        SqlConnection conn = new SqlConnection("server=(local);uid=sa;pwd=mssql;database=Test");
        SqlCommand cmd = conn.CreateCommand();
        cmd.CommandText = "select roles from users where username=@username and password=@password";
        //添加参数以及给参数赋值  
        cmd.Parameters.Add("@username", SqlDbType.VarChar, 64);
        cmd.Parameters["@username"].Value = this.TextBox1.Text;
        cmd.Parameters.Add("@password", SqlDbType.VarChar, 128);
        cmd.Parameters["@password"].Value = this.TextBox2.Text;
        //打开数据库连接  
        conn.Open();
        //执行命令  
        SqlDataReader reader = cmd.ExecuteReader();
        if (reader.Read())
        {

            //FormsAuthentication.SetAuthCookie("sanlang", false);

            //创建一个新的验证票FormsAuthenticationTicket  
         
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            1,//票版本号  
            this.TextBox1.Text,//cookie名字  
            DateTime.Now,//生成cookie时间  
            DateTime.Now.AddMinutes(30),//cookie的有效时间  
            false,//是不是永久存在的cookie  
            reader.GetString(0));//从数据库读到的用户角色数据  

 

            //把验证票加密  
            string hashTicket = FormsAuthentication.Encrypt(ticket);
            //设置验证票cookie,第一个参数为cookie的名字,第二个参数为cookie的值也就是加密后的票  
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
            //设置cookie的有效期是一个礼拜  
            //cookie.Expires = DateTime.Now.AddDays(1);
            //把cookie加进Response对象发生到客户端  
            Response.Cookies.Add(cookie);
            //得到请求的url  
            string requestUrl = FormsAuthentication.GetRedirectUrl(FormsAuthentication.FormsCookieName, false);
            //不要使用FormsAuthentication.RedirectFromLoginPage方法,因为这个方法会重写cookie  
            //重新定向到请求的url  
            Response.Redirect(requestUrl);
        }
        else
        {
            //如果不存在此用户,则提示一些错误  
            this.Label3.Text = "用户名或者密码错误,请重试!";
            this.Label3.Visible = true;
        }
        //关闭数据库连接和reader  
        reader.Close();
        conn.Close();  

说明:

我们来看下Forms身份验证基本原理:  
  一   身份验证  
  要采用Forms身份验证,先要在应用程序根目录中的Web.config中做相应的设  
  置:  
  <authentication   mode="Forms">    
          <forms   name=".ASPXAUTH"   loginUrl="login.aspx"   timeout="30"    
  path="/"/>  
  </authentication>  
  其中<authentication   mode="Forms">   表示本应用程序采用Forms验证方  
  式。  
  <forms>标签中的name表示指定要用于身份验证的Cookie。默认是.ASPXAUTH,其实你可以用任何名字,这也就是你在本地硬盘上看到的cookie里面的前面的几个字.  
  Forms的验证过程如下:1,生成身份验证票,2,加密身份验证票.3,写回客户端,4,浏览器重新定向.其实这一系列的动作如果我们不用roles的话都是通过FormsAuthentication.RedirectFromLoginPage方法来完成了这一系列的工作任务.但是既然我们要使用roles授权,我们就不能够使用这个方法,而要分开来,一步步完成.  
  首先是创建身份验证票,首先我们看看FormsAuthenticationTicket类的一个构造函数:  
  public   FormsAuthenticationTicket(  
  int   version,   //设为1  
  string   name,   //用户标示  
  DateTime   issueDate,   //Cookie   的发出时间,   设置为   DateTime.Now    
  DateTime   expiration,   //过期时间  
  bool   isPersistent,   //是否持久性(根据需要设置,若是设置为持久性,在发出  
  cookie时,cookie的Expires设置一定要设置)  
  string   userData,   //这里用上面准备好的用逗号分割的role字符串  
  string   cookiePath   //   设为”/”,这要同发出cookie的路径一致,因为刷新cookie  
  要用这个路径  
  );  
  最后个参数可以省略  
  FormsAuthenticationTicket   Ticket   =   new   FormsAuthenticationTicket    
  (1,”kent”,DateTime.Now,   DateTime.Now.AddMinutes(30),   false,UserRoles)  
   
  然后加密:  
   
  string   hashTicket   =   FormsAuthentication.Encrypt(ticket);  
  //设置验证票cookie,第一个参数为cookie的名字,第二个参数为cookie的值也就是加密后的票  
  HttpCookie   cookie   =   new   HttpCookie(FormsAuthentication.FormsCookieName,hashTicket);  
  //设置cookie的有效期是一个礼拜  
  cookie.Expires   =   DateTime.Now.AddDays(7);  
  //把cookie加进Response对象发生到客户端  
  Response.Cookies.Add(cookie);  
  //得到请求的url  
  string   requestUrl   =   FormsAuthentication.GetRedirectUrl(FormsAuthentication.FormsCookieName,false);  
  //不要使用FormsAuthentication.RedirectFromLoginPage方法,因为这个方法会重写cookie  
  //重新定向到请求的url  
  Response.Redirect(requestUrl);   
 

web.config

<?xml version="1.0"?>
<!--
    注意: 除了手动编辑此文件以外,您还可以使用
    Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的
     “网站”->“Asp.Net 配置”选项。
    设置和注释的完整列表在
    machine.config.comments 中,该文件通常位于
    /Windows/Microsoft.Net/Framework/v2.x/Config 中
-->
<configuration>
 <appSettings/>
 <connectionStrings/>
 <system.web>
    <compilation debug="true"/>
  <authentication mode="Forms">
   <forms name="MYWEBAPP.ASPXAUTH" loginUrl="login.aspx" protection="All" path="/"/>
  </authentication>
  <authorization>
   <allow users="*"/>
  </authorization>
  </system.web>
 <location path="admins">
  <system.web>
   <authorization>
    <!--   Order   and   case   are   important   below   -->
    <allow roles="Administrator"/>
    <deny users="*"/>
   </authorization>
  </system.web>
 </location>
 <location path="users">
  <system.web>
   <authorization>
    <!--   Order   and   case   are   important   below   -->
    <allow roles="User"/>
    <deny users="*"/>
   </authorization>
  </system.web>
 </location>
</configuration>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 答案:下面是一段python form表单提交脚本:import requestsurl = 'http://www.example.com/form-endpoint'mydata = {'name': 'John Smith', 'email': 'john@example.com'}x = requests.post(url, data = mydata)print(x.text) ### 回答2: 当您需要一段Python的表单提交脚本时,您可以使用Python的requests库来处理HTTP请求。以下是一个简单的示例代码: ```python import requests url = 'http://example.com/submit' data = {'name': 'John', 'age': 25, 'email': 'john@example.com'} response = requests.post(url, data=data) if response.status_code == 200: print('表单提交成功!') else: print('表单提交失败!') ``` 在这个示例中,我们首先导入了requests库。然后,我们定义了要提交表单的URL,并创建了一个包含表单数据的字典。在这个例子中,我们假设表单包含名字、年龄和电子邮件字段。 接下来,我们使用requests库的post方法向指定的URL发送POST请求,并将表单数据作为参数传递。最后,我们检查响应的状态码来判断表单提交是否成功。 请注意,这只是一个简单的示例,您可能需要根据实际情况进行相应的调整。例如,如果表单包含文件上传或需要进行身份验证,您可能需要使用requests库的其他功能来满足您的需求。 希望这段代码对您有所帮助! ### 回答3: 当我需要一段Python的form表单提交脚本时,我可以使用Python的requests库来实现。首先,我需要导入requests库: import requests 然后,我可以定义一个函数,该函数将通过POST请求将表单数据提交到目标网址。 def submit_form(url, data): response = requests.post(url, data=data) if response.status_code == 200: print("表单提交成功!") else: print("表单提交失败!") 在这里,url参数表示目标网址,data参数表示要提交的表单数据,它应该是一个字典类型。然后,我可以使用该函数来提交表单。 url = "http://example.com/submit" # 假设目标网址为http://example.com/submit data = { "name": "张三", "age": 20, "email": "zhangsan@example.com" # 其他表单字段及其值 } submit_form(url, data) 在这个例子中,我将name字段设置为"张三",age字段设置为20,email字段设置为"zhangsan@example.com"。你可以根据具体的表单要求来修改这些字段和值。 最后,根据服务器的响应状态码,我们可以判断表单是否成功提交。如果状态码为200,表示提交成功;否则,表示提交失败。 这就是我使用Python实现的一个简单的form表单提交脚本。根据实际需求,你可以根据需要修改脚本中的url和data参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值