.NET 下的Form认证
点击次数:75 次 发布日期:2008-11-06 07:50:02 作者:源代码网
|
<!--Form认证设置Start--> <authentication mode="Forms"> <forms name=".FrameWork" defaultUrl="Default.aspx" loginUrl="Login.aspx" enableCrossAppRedirects="true" path="/"></forms> </authentication> <authorization> <deny users="?"/> <!--allow users="*"/--> </authorization> <!--Form认证设置End--> 以上在登录站点时将不允许匿名登录。 二、一般目录可匿名访问的文件 可在configuration节点内做如下设置: <!-- 排除不需要验证的目录或文件--> <location path="Messages.aspx"> <system.web> <authorization> <allow users="*"/> </authorization> </system.web> </location> 三、转网友介绍的方法,比较简单易懂 登录时,如下操作: (1) 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); } } (2) 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 使用框架结构的系统。 退出登录时,如下操作: private void Btn_LogOut_Click(object sender, System.EventArgs e) { System.Web.Security.FormsAuthentication.SignOut(); } 四、如何判断验证与否及获取验证后的用户信息 有的时候,在同一张页面需要判断用户是否已经登录,然后再呈现不同的布局。 if(User.Identity.IsAuthenticated) { //你已通过验证 //用户操作代码 } User.Identity 还有两个属性AuthenticationType(验证类型)与 Name(用户名称) 五、使用web.config 应用程序的每个目录都可以新建一个web.config,它可“继承”并“重写”根目录的web.config设置内容。 <?xmlversion="1.0"encoding="utf-8"?> <configuration> <system.web> <authorization> <allowusers="Admin"/> <denyusers="*"/> </authorization> </system.web> </configuration> 源代码网推荐 源代码网供稿. |
