ASP.NET揭秘笔记之七
使用基于表单的验证
基于表单的验证可以把用户名和密码保存到任何你所期望的存储机制中。如Web.config文件\XML文件或数据库表中。
表单验证依赖于Cookie来确定用户 身份。
1、启用表单验证
首先修改Web.Config,启动表单验证模式。
<Configuration>
<System.Web>
<authentication mode="Forms"/>
</System.Web>
</Configuration>
<Configuration>
<System.Web>
<authorization>
<deny users="?" />
<!-- 拒绝匿名用户访问目录中的页面,其中“?”表示所有匿名用户。-->
</authorization>
</System.Web>
</Configuration>如果要让用户访问特定子目录中的文件。那么web.config中可以添加
<Configuration>
<System.Web>
<authorization>
<allow users="?" />
<!-- 允许所有的匿名用户访问 --->
</authorization>
</System.Web>
</Configuration>
Sub btnOk_Click(s as Object,e As EventArgs)
if txtUserName.Text.Trim="Bill Gates" And txtPWD.Text.Trim="Test Password" Then
'//RedirectFromLoginPage方法通过使用浏览器重定向,也会自动把用户重定向回到最初发送用户到Login.aspx页面的那个页面上
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text,chkRememberMe.Checked)
else
lblMessage.Text="用户名或密码错误!"
end if
End SubRedirectFromLoginPage方法重定向用户回到由Return-Url查询字符串变量表示的页面。如果用户直接连接到Login.aspx页面,那么Return-Url查询字符串变量并不包会包含值。在这种情况下,RedirectFromLoginPage重定向用户到Default.aspx页面。
配置表单验证:
WebConfig的Authentication字节可以包含一个可选的Forms元素,该元素属性如下:
LoginUrl。在要求验证时,把用户重定向到的页面,在默认情况下,被重定向到Login.aspx
name 包含验证令牌的浏览器Cookie名称,默认值为 .ASPXAUTH。但是如果在多个服务器上配置多个应用程序,那么应当为每个应用程序提供一个唯一性的Cookie名。
TimeOut 在Cookie过期前的时间数,单位为分钟。默认值为30分钟。这个属性值不会用到持久性Cookie
Path 用于Cookie的路径,默认值为"/"
Protection 保护Cookie数据的方法,可选值有 all, none,encryption和validation,默认值为 all。
<Configuration>
<System.Web>
<authentication mode="forms">
<forms
name=".MyCookie"
loginUrl="/login/mylogin.aspx"
protection="All"
timeout="80"
path="/" />
</authentication>
</System.Web>
</Configuration>获取用户信息:
使用表单验证来验证用户身份是由FormsIdentity类来实现的,可以使用以下的类来获取一个已经验证的用户信息
AuthenticationType ---总是返回Forms值
IsAuthenticated ----表示用户是否已经验证
Name----表示已验证的用户的名称
Ticket ----指定与当前用户关联的Cookie验证令牌
Ticket属性表示验证令牌,FormsAuthenticationTicket类具有如下属性
CookiePath ---验证令牌Cookie的路径
Expiration---验证令牌Cookie过期的日期
Expired ---表示当前验证令牌是否已经过期。Boolean类型
IsPersistent---表示验证令牌是否包含在持久性Cookie的值
IssueDate---创建包含验证令牌的Cookie的日期和时间
Name---与验证令牌关联的用户名
UserDate---可以在验证令牌中包含的 自定义数据
Version ----一个整数,表示验证令牌的版本号,默认值为0
可以通过下面的程序显示出这些属性:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'在此处放置初始化页的用户代码
Dim objUserIdentity As FormsIdentity
Dim objTicket As FormsAuthenticationTicket
If User.Identity.IsAuthenticated Then
objUserIdentity = User.Identity
objTicket = objUserIdentity.Ticket
Response.Write("Name: " & objUserIdentity.Name & "<br>")
Response.Write("Expiration: " & objTicket.Expiration & "<br>")
Response.Write("Expired: " & objTicket.Expired & "<br>")
Response.Write("IsPersistent: " & objTicket.IsPersistent & "<br>")
Response.Write("IssueDate: " & objTicket.IssueDate & "<br>")
Response.Write("UserDate: " & objTicket.UserData & "<br>")
Response.Write("Version: " & objTicket.Version & "<br>")
End If
End Sub创建登出页面:
使用FormsAuthentication类的SignOut方法
Sub_PageLod
FormsAuthentication.SignOut()
End Sub
在梦想和现实之间寻找平衡 在欲望和理想之间左右的妥协!平淡又平凡的努力生活!


浙公网安备 33010602011771号