欢迎光临
我们一直在努力

在ASP.NET中如何用C#.NET实现基于表单的验证-.NET教程,C#语言

建站超值云服务器,限时71元/月

这篇文章引用到了microsoft .net类库中的以下名空间:
system.data.sqlclient
system.web.security
-------------------------------
任务:
摘要: 
  1.要求
    2.用visual c#.net 创建一个asp.net 应用程序
  3.在web.config文件里配置安全设置
  4.创建一个数据库表样例来存放用户资料
  5.创建logon.aspx页面
  6.编写事件处理代码来验证用户身份
  7.创建一个default.aspx页面
  8.附加提示
参考文章
-------------------------------
摘要
 这篇文章示范了如何实现通过数据库存储用户信息来实现基于表单的验证.
(一)要求
 需要以下工具来实现
1.microsoft visual studio.net
2.microsoft internet information services(iis) version 5.0 或者更新
3.microsoft sql server
(二)用c#.net创建asp.net应用程序
1.打开visual studio.net
2.建立一个新的asp.net web应用程序,并且指定名称和路径.
(三)在web.config文件里配置安全设置
这一节示范了如何通过添加和修改<authentication>和<authorization>节点来配置asp.net应用程序以实现基于表单的验证.
1.在解决方案窗口里,打开web.config文件.
2.把authentication模式改为forms(注:默认为windows)
3.插入<forms>标签,并且填入适当的属性.(请链接到在文章最后列出的msdn文档或者quickstart文档来查看这些属性)先复制下面的代码,接着再把它粘贴到<authentication>节:

<authentication mode=”forms”>
<form name=”.aspxformsdemo” loginurl=”logon.aspx” protection=”all” path=”/” timeout=”30″/>
</authentication>
(注:如果不指定loginurl,默认为default.aspx)

4.通过加入以下节点实现拒绝匿名访问:
<authentication>
<deny users=”?”/>
<allow users=”*”/>
</authentication>

(四)创建一个数据库表样例来存放用户资料
这一节示范了如何创建一个示例数据库来存放用户名,密码,和用户角色.如果你想要实现基于角色的安全就有必要在数据库中添加一个存放用户角色的字段.
1.打开记事本。
2.把下面这段脚本复制到记事本然后保存:

if exists (select * from sysobjects where id =
object_id(n[dbo].[users]) and objectproperty(id, nisusertable) = 1)
drop table [dbo].[users]
go
create table [dbo].[users] (
   [uname] [varchar] (15) not null ,
   [pwd] [varchar] (25) not null ,
   [userrole] [varchar] (25) not null ,
) on [primary]
go
alter table [dbo].[users] with nocheck add
   constraint [pk_users] primary key  nonclustered
   (
      [uname]
   )  on [primary]
go

insert into users values(user1,user1,manager)
insert into users values(user2,user2,admin)
insert into users values(user3,user3,user)
go
3.打开microsoft sql server,打开查询分析器,在数据库列表里选择pubs数据库,然后把上面的脚本粘贴过来,运行。这时会在pubs数据库里创建一个将会在这个示例程序中用到的示例用户表。
(五)创建logon.aspx页面
1.在已创建好的项目里创建一个新的web 窗体,名为logon.aspx。
2.在编辑器里打开logon.aspx,切换到html视图。
3.复制下面代码,然后在编辑菜单里“选择粘贴为html”选项,插入到<form>标签之间。
<h3>
   <font face=”verdana”>logon page</font>
</h3>
<table>
   <tr>
      <td>email:</td>
      <td><input id=”txtusername” type=”text” runat=”server”></td>
      <td><asp:requiredfieldvalidator controltovalidate=”txtusername”
           display=”static” errormessage=”*” runat=”server”
           id=”vusername” /></td>
   </tr>
   <tr>
      <td>password:</td>
      <td><input id=”txtuserpass” type=”password” runat=”server”></td>
      <td><asp:requiredfieldvalidator controltovalidate=”txtuserpass”
          display=”static” errormessage=”*” runat=”server”
          id=”vuserpass” />
      </td>
   </tr>
   <tr>
      <td>persistent cookie:</td>
      <td><asp:checkbox id=”chkpersistcookie” runat=”server” autopostback=”false” /></td>
      <td></td>
   </tr>
</table>
<input type=”submit” value=”logon” runat=”server” id=”cmdlogin”><p></p>
<asp:label id=”lblmsg” forecolor=”red” font-name=”verdana” font-size=”10″ runat=”server” />

 这个页面用来显示一个登录表单以便用户可以提供他们的用户名和密码,并且记录到应用程序中。
4.切换到设计视图,保存这个页面。

(六)编写事件处理代码来验证用户身份
 下面这些代码是放在后置代码页里的(logon.aspx.cs)
1.双击logon页面打开logon.aspx.cs文件。
2.在后置代码文件里导入必要的名空间:
  using system.data.sqlclient;
  using system.web.security;
3.创建一个validateuser的函数,通过在数据库中查找用户来验证用户的身份。(请改变菘饬幼址粗赶蚰愕氖菘猓?br>private bool validateuser( string username, string password )
{
sqlconnection conn;
sqlcommand cmd;
string lookuppassword = null;

// check for invalid username.
// username must not be null and must be between 1 and 15 characters.
if ( (  null == username ) || ( 0 == username.length ) || ( username.length > 15 ) )
{
  system.diagnostics.trace.writeline( “[validateuser] input validation of username failed.” );
  return false;
}

// check for invalid password.
// password must not be null and must be between 1 and 25 characters.
if ( (  null == password ) || ( 0 == password.length ) || ( password.length > 25 ) )
{
  system.diagnostics.trace.writeline( “[validateuser] input validation of password failed.” );
  return false;
}

try
{
  // consult with your sql server administrator for an appropriate connection
  // string to use to connect to your local sql server.
  conn = new sqlconnection( “server=localhost;integrated security=sspi;database=pubs” );
  conn.open();

  // create sqlcommand to select pwd field from users table given supplied username.
  cmd = new sqlcommand( “select pwd from users where uname=@username”, conn );
  cmd.parameters.add( “@username”, sqldbtype.varchar, 25 );
  cmd.parameters[“@username”].value = username;

  // execute command and fetch pwd field into lookuppassword string.
  lookuppassword = (string) cmd.executescalar();

  // cleanup command and connection objects.
  cmd.dispose();
  conn.dispose();
}
catch ( exception ex )
{
  // add error handling here for debugging.
  // this error message should not be sent back to the caller.
  system.diagnostics.trace.writeline( “[validateuser] exception ” + ex.message );
}

// if no password found, return false.
if ( null == lookuppassword )
{
  // you could write failed login attempts here to event log for additional security.
  return false;
}

// compare lookuppassword and input password, using a case-sensitive comparison.
return ( 0 == string.compare( lookuppassword, password, false ) );

}
(注:这段代码的意思是先判断输入的用户名和密码是否符合一定的条件,如上,如果符合则连接到数据库,并且根据用户名来取出密码并返回密码,最后再判断取出的密码是否为空,如果不为空则再判断取出的密码和输入的密码是否相同,最后的false参数为不区分大小写)

4.在cmdlogin_serverlick事件里使用下面两种方法中的一种来产生表单验证的cookie并将页面转到指定的页面。
下面提供了两种方法的示例代码,根据你的需要来选择。
a)在cmdlogin_serverclick事件里调用redirectfromloginpage方法来自动产生表单验证cookie且将页面定向到一个指定的页面。
private void cmdlogin_serverclick(object sender,system.eventargs e)
{
  if(validateuser(txtusername.value,txtuserpass.value))

   formsauthentication.redirectfromloginpage(txtusername.value,chkpresistcookie.checked);
   else
    response.redirect(“logon.aspx”,true);   

}

b)产生加密验证票据,创建回应的cookie,并且重定向用户。这种方式给了更多的控制权去让你如何去创建cookie,你也可以连同formsauthenticationticket一起包含一些自定义的数据。
private void cmdlogin_serverclick(object sender,system.eventargs e)
{
  if(validateuser(txtusername.value,txtuserpass.value))
  {
   formsauthenticationticket tkt;
   string cookiestr;
   httpcookie ck;
   tkt=new formsauthenticationticket(1,txtusername.value,datetime.now,datetime.now.addminutes(30),chkpersistcookie.checked,”your custom data”); //创建一个验证票据
   cookiestr=formsauthentication.encrypt(tkt);//并且加密票据
   ck=new httpcookie(formsauthentication.formscookiename,cookiestr);// 创建cookie
   if(chkpersistcookie.checked) //如果用户选择了保存密码
    ck.expires=tkt.expiratioin;//设置cookie有效期
    ck.path=formsauthentication.formscookiepath;//cookie存放路径
   response.cookies.add(ck);
   string strredirect;
   strredirect=request[“returnurl”];
   if(strredirect==null)
    strredirect=”default.aspx”;
   response.redirect(strredirect,true);
  }
  else
   reponse.redirect(“logon.aspx”,true);
}
  5.请确保在inititalizecomponent方法里有如下代码:
   this.cmdlogin.serverclick += new system.eventhandler(this.cmdlogin_serverclick);
  
(七)创建一个default.aspx页面
这一节创建一个测试页面用来作为当用户验证完之后重定向到的页面。如果用户第一次没有被记录下来就浏览到这个页,这时用户将被重定向到登录页面。
  1.把现有的webform1.aspx重命名为default.aspx,然后在编辑器里打开。

  2.切换到html视图,复制以下代码到<form>标签之间:
<input type=”submit” value=”signout” runat=”server” id=”cmdsignout”>
这个按钮用来注销表单验证会话。
  3.切换到设计视图,保存页面。
  4.在后置代码里导入必要的名空间:
using system.web.security;
  5.双击singout按钮打开后置代码(default.aspx.cs),然后把下面代码复制到cmdsingout_serverclick事件处理中:
  private void cmdsignout_serverclick(object sender,system.eventargs e)
  {
   formsauthentication.signout();//注销
   response.redirect(“logon.aspx”,true);
  }
  6.请确认在inititalizecomponent方法中有以下代码:
  this.cmdsignout.serverclick += new system.eventhandler(this.cmdsignout_serverclick);
  7.保存编译项目,现在可以运行这个应用程序了。
(八)附加提示
  1.如果想要在数据库里安全地存放密码,可以在存放到数据到之前先用formsauthentication类里的hashpasswordforstoringinconfigfile函数来加密。(注:将会产生一个哈希密码)
  2.可以在配置文件(web.config)里存放sql连接信息,以便当需要时方便修改。
  3.可以增加一些代码来防止黑客使用穷举法来进行登录。例如,增加一些逻辑使用户只能有两三次的登录机会。如果用户在指定的登录次数里无法登录的话,可以在数据库里设置一个标志符来防止用户登录直到此用户访问另一个页面或者请示你的帮助。另外,也可以在需要时增加一些适当的错误处理。
  4.因为用户是基于验证cookie来识别的,所以可以在应用程序里使用安全套接层(ssl)来保护验证cookie和其它有用的信息。
  5.基于表单的验证方式要求客户端的游览器接受或者启用cookies.
  6.在<authentication>配置节里的timeout参数用来控制验证cookies重新产生的间隔时间。可以给它赋一个适当的值来提供更好的性能和安全性。
  7.在internet上的一些代理服务器或者缓冲可能会缓存一些将会重新返回给另外一个用户的包含set-cookie头的web服务器响应。因为基于表单的验证是使用cookie来验证用户的,所以通过中间代理服务器或者缓冲的话可能会引起用户会被意外地搞错为原本不是要发送给他的用户。
   
   
参考文章:
  如果想要知道如何通过配置<credentials>节点存放用户名和密码来实现基于表单的验证的话,请参考以下gotdotnet asp.net quickstart示例:
  基于表单的验证:http://www.gotdotnet.com/quickstart/aspplus/default.aspx?url=/quickstart/aspplus/doc/formsauth.aspx
  如果想要知道如何使用xml文件来存放用户名和密码来实现基于表单的验证的话,请参考sdk文档的以下示例:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcookieauthenticationusinganxmlusersfile.asp
  如果想要知道更多的关于asp.net安全的话,请参考microsoft .net framework developers guide文档:
asp.net 安全:  http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconaspnetwebapplicationsecurity.asp
   如果想知道更多关于system.web.security名空间的话,请参考:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemwebsecurity.asp
  如果想知道更多的关于asp.net配置的话,请参考microsoft .net framework developers guide文档:
asp.net配置:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconaspnetconfiguration.asp
asp.net配置节点:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpgrfaspnetconfigurationsections.asp
  如果想知道更多关于asp.net安全指导的话,请参考msdn:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/authaspdotnet.asp
  如果想知道更多关于asp.net的,请参考msdn新闻组:
http://go.microsoft.com/fwlink/?linkid=5811&clcid=0x409

这篇文章适用于:
microsoft asp.net (included with the .net framework 1.1)
microsoft visual c# .net (2003)
microsoft asp.net (included with the .net framework) 1.0
microsoft visual c# .net (2002)
microsoft sql server 2000 (all editions)
microsoft sql server 7.0
microsoft sql server 2000 64 bit (all editions)

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 在ASP.NET中如何用C#.NET实现基于表单的验证-.NET教程,C#语言
分享到: 更多 (0)