ASP.NET 的安全认证,共有“Windows”“Form”“Passport”“None”四种验证模式。“Windows”与“None”没有起到保护的作用,不推荐使用;“Passport”我又没用过,唉……所以我只好讲讲“Form”认证了。我打算分三部分: 

第一部分 —— 怎样实现From 认证; 

第二部分 —— Form 认证的实战运用; 

第三部分 —— 实现单点登录(Single Sign On) 

第一部分 如何运用 Form 表单认证 

一、     新建一个测试项目 

为了更好说明,有必要新建一个测试项目(暂且为“FormTest”吧),包含三张页面足矣(Default.aspx、Login.aspx、UserInfo.aspx)。啥?有人不会新建项目,不会新增页面?你问我咋办?我看这么办好了:拖出去,打回原藉,从幼儿园学起…… 

二、     修改 Web.config 

1、 双击项目中的Web.config(不会的、找不到的打 PP) 

2、 找到下列文字 <authentication mode="Windows" /> 把它改成:

<authentication mode="Forms"> 

<forms loginUrl="Login.aspx" name=".ASPXAUTH"></forms> 

</authentication> 

3、 找到<authorization> <allow users="*" /></authorization>换成 

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

这里没什么好说的,只要拷贝过去就行。虽说如此,但还是有人会弄错,如下: 

<authentication mode="Forms"> 

    
<forms loginUrl="Login.aspx" name=".APSX"></forms> 

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

</authentication> 

若要问是谁把 
<deny users="?"></deny> 放入 <authentication> 中的,我会很荣幸地告诉你,那是 N 年前的我:<authentication> 与 <authorization> 都是以 auth 字母开头又都是以 ation 结尾,何其相似;英文单词背不下来的我以为他们是一伙的…… 

三、     编写 .cs 代码——登录与退出 

1、 登录代码: 

a、 书本上介绍的 

      
private void Btn_Login_Click(object sender, System.EventArgs e) 

      


        
if(this.Txt_UserName.Text=="Admin" && this.Txt_Password.Text=="123456"

        


  System.Web.Security.FormsAuthentication.RedirectFromLoginPage(
this.Txt_UserName.Text,false); 

  }
 

}
 

b、 偶找了 N 久才找到的 

private void Btn_Login_Click(object sender, System.EventArgs e) 

      

        
if(this.Txt_UserName.Text=="Admin" && this.Txt_Password.Text=="123456"
        


System.Web.Security.FormsAuthentication.SetAuthCookie(
this.Txt_UserName.Text,false); 

  Response.Redirect(
"Default.aspx"); 

  }
 
}
 

以上两种都可发放验证后的 Cookie ,即通过验证,区别: 

方法 a) 指验证后返回请求页面,俗称“从哪来就打哪去”。比如:用户没登录前直接在 IE 地址栏输入 http:
//localhost/FormTest/UserInfo.aspx ,那么该用户将看到的是 Login.aspx?ReturnUrl=UserInfo.aspx ,输入用户名与密码登录成功后,系统将根据“ReturnUrl”的值,返回相应的页面 

方法 b) 则是分两步走:通过验证后就直接发放 Cookie ,跳转页面将由程序员自行指定,此方法多用于 Default.aspx 使用框架结构的系统。 

2、 退出代码: 

private void Btn_LogOut_Click(object sender, System.EventArgs e) 
  


System.Web.Security.FormsAuthentication.SignOut(); 

}
 

四、     如何判断验证与否及获取验证后的用户信息 

有的时候,在同一张页面需要判断用户是否已经登录,然后再呈现不同的布局。有人喜欢用 Session 来判断,我不反对此类做法,在此我只是想告诉大家还有一种方法,且看下面代码: 

if(User.Identity.IsAuthenticated) 
  


        
//你已通过验证,知道该怎么做了吧? 

}
 

posted on 2007-02-04 09:43  ipusr  阅读(249)  评论(0)    收藏  举报