forms 身份验证(授权)详解

首先在 web.config 中设置

<authentication mode="Forms">设置 mode="Forms"
  <forms loginUrl="login.aspx" name="boyang" protection="All"></forms>  加密和保护
    </authentication>
    <authorization>在这个里面设置那些用户被容许和拒绝
      <deny users="?,a"/>拒绝  ?代表匿名 *代表所有人
      <allow users ="b"/>容许
    </authorization>
   
在和数据库比较时,如果通过则写入数据库,方法如下,2种都可以
      1  //System.Web.Security.FormsAuthentication.SetAuthCookie(this.TextBox1.Text,false); 把信息写入cookies、false 代表cookies 不保存
        // Response.Redirect("login.aspx");返回指定页面
    2    System.Web.Security.FormsAuthentication.RedirectFromLoginPage(this.TextBox1.Text,true);//信息写入cookies并返回之前的页面  cookies保存


         System.Web.Security.FormsAuthentication.SignOut();  //删除保存的cookies,等于退出登陆。

下面我们通过一个示例来学习一下用户少的情况下,不用数据库直接验证用户和密码。
比如有3个用户,在forms 中加入红色部分
 <forms loginUrl="login.aspx" name="boyang" protection="All">
        <credentials passwordFormat="Clear">//密码格式有3种 md5 sha1 和 clear  clear 是明文密码md5是md5加密 、sha1 也是加密
如果是md5或者sha1则下面密码应该是加密后的字符串,即使别人看见了也解不开的,
如<user name="bo" password="ADGSFJHFJFJHFJBCBFG">

          <user name="bo" password="bo"/>
          <user name="mm" password="mm"/>
          <user name="pp" password="pp"/>
        </credentials>
      </forms>

  <deny users="?"/>      
    </authorization>

在login.aspx(有2个文本框和一个按钮 )中验证可以用以下方法
if(System.Web.Security.FormsAuthentication.Authenticate(TextBox1.Text,TextBox2.Text))  比较用户和密码是否在中,如果在则返回 true
TextBox1.Text 和  TextBox2.Text 分别对应用户和密码

然后写入cookes 就可以了

System.Web.Security.FormsAuthentication.SetAuthCookie(this.TextBox1.Text);这样就完成了验证。


由于这种方式密码是明文的,所以很不安全,我们可以用MD5 和 SHA1 方法实现
首先设置  passwordFormat="MD5 " password ="加密后的字符串",

验证还是  System.Web.Security.FormsAuthentication.Authenticate(TextBox1.Text,TextBox2.Text) 他会自动 把TextBox2.Text 加密然后比较

加密mdb密码方法:   System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox2.Text, "MD5");

加密sha1密码方法:   System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox2.Text, "SHA1");


这样就实现加密登陆了 。


如果想停止一个用户(如 bo),可以在下面 <deny users="bo"/>把bo 加入 拒绝用户,就可以了。虽然他可以通过登陆,但验证时会出错。    

posted @ 2006-03-30 16:58  New Yang Bo Element  阅读(1319)  评论(0编辑  收藏  举报