asp.net中使用窗体身份验证
2008-09-09 18:15
585 查看
代码下载:基于角色的窗体身份验证示例代码
经常看到一些网友,自己写一些代码,判断用户是否登录,判断用户权限,例如使用Session,Cookie等,实际上微软替我们做好这些事情了,我们要做的只是调用一下。节省出时间可以去www.svnhost.cn看看。
好了,废话不说,直接来代码吧!
第一步:设置web.config
<authentication mode="Forms"></authentication>,如果web.config中已经有authentication 只要添加mode="Forms"节或者可能默认是mode="Windows",修改成如上即可。
第二步:新建一个独立用户登录的类:
第三步:添加具体登录退出细节,新建login.aspx页面,注意,这里如果建立Login.aspx页面,有可能后台类Login和系统的Login控件冲突,这时修改下类名即可。
login.aspx.cs代码:
退出Logout.aspx文件,后台代码如下:
至此登录和退出都有了,如果整个文件夹需要验证登录才能访问?在web.config中设置如下:
<location path="User">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
表示User目录,禁止匿名用户访问。即用户管理中心。
如果需要对登录用户也区别对待?这时用“角色”来处理就最方便了。首先需要建立如下类,该类是用来恢复用户身份和角色用的:
web.config设置如下:
<httpModules>
<add name="MyHttpModule" type="BLL.MyHttpModule,BLL"></add>
</httpModules>
这样就启用角色了。然后在web.config里设置:
<location path="Admin">
<system.web>
<authorization>
<allow roles="admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
表示只允许admin角色成员可以访问Admin目录,即网站管理后台。这是传递角色u.Roles为"admin"即可,多个角色可以用逗号分开。
其他文件中使用User:
调用代码:User.Identity.IsAuthenticated返回用户是否登录,User.IsInRole("admin")返回用户是否属于admin组。以上过程看起来蛮复杂,实际开发好以后,每次只要把相应的文件复制过来即可。非常方便。而且是基于角色的窗体身份验证哦~!安全性非常高。
代码下载:基于角色的窗体身份验证示例代码
经常看到一些网友,自己写一些代码,判断用户是否登录,判断用户权限,例如使用Session,Cookie等,实际上微软替我们做好这些事情了,我们要做的只是调用一下。节省出时间可以去www.svnhost.cn看看。
好了,废话不说,直接来代码吧!
第一步:设置web.config
<authentication mode="Forms"></authentication>,如果web.config中已经有authentication 只要添加mode="Forms"节或者可能默认是mode="Windows",修改成如上即可。
第二步:新建一个独立用户登录的类:
using System; using System.Collections.Generic; using System.Text; using System.Web; using System.Web.Security; namespace BLL { /// <summary> /// 用户实用类 /// </summary> public sealed class UserUtil { public static void Login(string username, string roles, bool isPersistent) { DateTime dt = isPersistent ? DateTime.Now.AddMinutes(99999) : DateTime.Now.AddMinutes(60); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // 票据版本号 username, // 票据持有者 DateTime.Now, //分配票据的时间 dt, // 失效时间 isPersistent, // 需要用户的 cookie roles, // 用户数据,这里其实就是用户的角色 FormsAuthentication.FormsCookiePath);//cookie有效路径 //使用机器码machine key加密cookie,为了安全传送 string hash = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); //加密之后的cookie //将cookie的失效时间设置为和票据tikets的失效时间一致 if (ticket.IsPersistent) { cookie.Expires = ticket.Expiration; } //添加cookie到页面请求响应中 HttpContext.Current.Response.Cookies.Add(cookie); } public static void Logout() { HttpCookie cookie = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName]; if (cookie == null) { cookie = new HttpCookie(FormsAuthentication.FormsCookieName); HttpContext.Current.Response.Cookies.Add(cookie); } cookie.Expires = DateTime.Now.AddYears(-10); } } }
第三步:添加具体登录退出细节,新建login.aspx页面,注意,这里如果建立Login.aspx页面,有可能后台类Login和系统的Login控件冲突,这时修改下类名即可。
login.aspx.cs代码:
//假设有UserInfo实体类,有UserInfo.GetUserInfoByPassword根据用户名,密码取用户的方法。chkCookie.Checked表示是否持久登录。true:下次打开浏览器自动登录。//u.Roles表示该用户的角色,如果没有启用角色的话,随便传值即可。 UserInfo u = UserInfo.GetUserInfoByPassword(txtUserName.Text, MD5(txtPassword.Text)); if (u!=null && u.UserId>0) { UserUtil.Login(u.UserName, u.Roles chkCookie.Checked); if (Request.QueryString["ReturnUrl"] != null && !Request.QueryString["ReturnUrl"].ToLower().Contains("login.aspx")) Response.Redirect(Request.QueryString["returnUrl"]); else Response.Redirect("/"); } else Label1.Text = "登录失败,可能是密码错误,请重新登录";
退出Logout.aspx文件,后台代码如下:
BLL.UserUtil.Logout(); if (Request.QueryString["returnUrl"] != null) Response.Redirect(Request.QueryString["returnUrl"], true); else Response.Redirect("~/");
至此登录和退出都有了,如果整个文件夹需要验证登录才能访问?在web.config中设置如下:
<location path="User">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
表示User目录,禁止匿名用户访问。即用户管理中心。
如果需要对登录用户也区别对待?这时用“角色”来处理就最方便了。首先需要建立如下类,该类是用来恢复用户身份和角色用的:
using System; using System.Web; using System.Text.RegularExpressions; using System.Configuration; using System.Collections; using System.Web.Security; using System.Security.Principal; using System.IO; namespace BLL { /// <summary> /// MyHttpModule 的摘要说明。 /// </summary> public class MyHttpModule : IHttpModule { public void Init(HttpApplication app) { app.AuthenticateRequest += new EventHandler(app_AuthenticateRequest); app.EndRequest += new EventHandler(app_EndRequest); } void app_EndRequest(object sender, EventArgs e) { foreach (string key in HttpContext.Current.Response.Cookies) { HttpContext.Current.Response.Cookies[key].Domain = ConfigurationManager.AppSettings["domain"];//这里可以保证你的cookie都是顶级域名下的,可以实现二级域名,N级域名登录 } } public void Dispose() { } private void app_AuthenticateRequest(object sender, EventArgs e) { // 提取窗体身份验证 cookie string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = HttpContext.Current.Request.Cookies[cookieName]; if (null == authCookie) { // 没有身份验证 cookie。 return; } FormsAuthenticationTicket authTicket = null; authTicket = FormsAuthentication.Decrypt(authCookie.Value); if (null == authTicket) { // 无法解密 Cookie。 return; } // 创建票证后,为 UserData 属性指定一个 // 以管道符分隔的角色名字符串。 string[] roles = authTicket.UserData.Split(new char[] { ',' }); // 创建一个标识对象 FormsIdentity id = new FormsIdentity(authTicket); // 该主体将通过整个请求。 GenericPrincipal principal = new GenericPrincipal(id, roles); // 将新的主体对象附加到当前的 HttpContext 对象 HttpContext.Current.User = principal; } } }
web.config设置如下:
<httpModules>
<add name="MyHttpModule" type="BLL.MyHttpModule,BLL"></add>
</httpModules>
这样就启用角色了。然后在web.config里设置:
<location path="Admin">
<system.web>
<authorization>
<allow roles="admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
表示只允许admin角色成员可以访问Admin目录,即网站管理后台。这是传递角色u.Roles为"admin"即可,多个角色可以用逗号分开。
其他文件中使用User:
调用代码:User.Identity.IsAuthenticated返回用户是否登录,User.IsInRole("admin")返回用户是否属于admin组。以上过程看起来蛮复杂,实际开发好以后,每次只要把相应的文件复制过来即可。非常方便。而且是基于角色的窗体身份验证哦~!安全性非常高。
代码下载:基于角色的窗体身份验证示例代码
相关文章推荐
- asp.net中使用窗体身份验证
- 如何使用 C# .NET 在 ASP.NET 应用程序中实现基于窗体的身份验证
- 如何使用 C# .NET 在 ASP.NET 应用程序中实现基于窗体的身份验证
- asp.net中使用窗体身份验证
- 使用 C# .NET 在 ASP.NET 应用程序中实现基于窗体的身份验证
- asp.net中使用窗体身份验证
- 使用 C# .NET 在 ASP.NET 应用程序中实现基于窗体的身份验证
- 如何使用 C# .NET 在 ASP.NET 应用程序中实现基于窗体的身份验证
- asp.net中使用窗体身份验证
- asp.net中使用窗体身份验证 [转]来源:小灰http://www.svnhost.cn/Article/Detail-23.shtml
- asp.net中使用窗体身份验证
- asp.net中使用窗体身份验证
- 如何使用 C# .NET 在 ASP.NET 应用程序中实现基于窗体的身份验证
- 如何使用 C# .NET 在 ASP.NET 应用程序中实现基于窗体的身份验证
- [导入]如何使用 C# .NET 在 ASP.NET 应用程序中实现基于窗体的身份验证
- ASP.Net 2.0 窗体身份验证机制-转+自己代码注释示例与更详细的说明
- ASP.net的窗体身份验证
- ASP.NET MVC5+MySql使用ASP.NET 身份验证
- ASP.NET 2.0 中的窗体身份验证
- ASP.Net:基于窗体的身份验证