ASP.net中的Forms认证方式

来源:互联网 发布:电脑软件没了 编辑:程序博客网 时间:2024/04/30 05:37
 

第一步:首先我们修改web.config文件为如下:

<authentication mode="Forms">

    <forms name="myhualong" loginUrl="login.aspx" path="/" timeout="30" protection="ALL"></forms>

</authentication>

<authorization>

    <deny users="?" />

</authorization>

注意,上面mode="Forms"中的F一定要大写,看csdn的asp.net电子杂志里面写的是forms,晕死,这不是误导吗?

name属性代表cookies的名字,我们可以起任意的名字,我们可以这样测试,如果我们使用了Forms验证而且保存了cookies,那么我们在本地硬盘的cookie文件夹中找到相对应的cookie名字,打开他我们就会发现这个cookie的内容是以这里的name属性所代表的值来开头的,在这里是myhualong

loginUrl代表如果用户没有登陆而访问任何页面的话都会首先被导向到这个loginUrl属性所对应值的页面,在这里是login.aspx

timeout代表cookies的有效期,是以分钟为单位的,这里是30分钟.

path="/" 我也不知道是什么意思,反正我写和不写都是一个样

protection代表保护类型,ALL全部大写。

第二步:我们在cs后台文件中导入名字空间:using System.Web.Security;

第三步:我们开始在登陆按钮的单击事件里写代码:

private void btnLogin_Click(object sender, System.Web.UI.ImageClickEventArgs e)
  {
   if(!IsValid)
   {
       Response.Write("<script>alert(&apos;用户名或密码错误!&apos;);</script>");
    return;
   }
   string connString = "provider=Microsoft.Jet.OleDb.4.0;Data Source=c:/inetpub/wwwroot/hualong/hualong.mdb";
   string selString = string.Format("select Count(*) from myuser where name = &apos;{0}&apos; and pass = &apos;{1}&apos;",txtName.Text.Trim(),txtPass.Text.Trim());
   OleDbConnection conn = new OleDbConnection(connString);
   OleDbCommand comm = new OleDbCommand(selString,conn);
   conn.Open();
   int i = (int)comm.ExecuteScalar();
   if(i>0)
   {
    FormsAuthentication.RedirectFromLoginPage(txtName.Text.Trim(),false);
   }
   else
   {
       Response.Write("<script>alert(&apos;用户名或密码错误!&apos;);</script>");
   }
            conn.Close();
  }

呵呵,写到这里可能问题来拉,因为FormsAuthentication.RedirectFromLoginPage(txtName.Text.Trim(),false);
是导向到原来用户所请求的页面,但是如果用户没有请求页面比如只输入:www.abc.com则看你在iis管理器中怎么样设置默认主文档的,如果你设置的默认主文档是index.aspx,则用户通过验证后请求www.abc.com被导向到www.abc.com/index.aspx,如果默认文档是default.aspx则用户通过验证后他的请求就会被导向到www.abc.com/defaul.aspx,但是如果我们想如果让用户通过验证后不是导向到默认的主文档而是被导向到另外个页面如manager.aspx该怎么样办呢?

其实很简单,陕北吴旗娃兄教我:FormsAuthentication.RedirectFromLoginPage(txtName.Text.Trim(),false);
就是相当于下面这两行代码:FormsAuthentication。SetAuthCookie(txtName.Text.Trim(),false);

Response.Redirect("manager.aspx");

这样不就解决问题了吗?你想导向到什么页面你就填写什么页面就是。

当然,为了安全,我们一般把数据库中的用户密码加密,在这个时候我们可以先把密码输入框中的密码加密后再做为查询检索条件查询数据库

string hashString = FormsAuthentication.HashPasswordForStringInConfigFile(txtPass.Text.Trim(),"SHAI");

这样我们就把密码框的内容用SHAI加密方法加密了。

陕北吴旗娃兄还教我:

用Forms认证设Cookie超时时间比较麻烦点,要用FormsAuthenticationTicket,但是我现在还没想到过在Forms验证里面设置cookies的有效期,所以暂时没去学习FormsAuthenticationTicket,等想学的时候再帖上来

原创粉丝点击