|
| 首页 → 程序开发 → .NET教程 |
| 阅读文章 |
雕虫小技--授权控件
开篇语 每个系统都有她的授权模块,很早就想把"授权模块"抽象出来,省得每次都做一些不必要的"机械运动":)再说,这样也可以降低系统的"偶合度". 很早其实就想到了,可以利用IHttpModule接口的验证和授权两个事件,来做点什么... 但是,后来发现在验证和授权两个事件中,压根不能使用Session,这怎么办了?放HttpApplication里吗?感觉不安全,就一值没有再想这个问题了... 后来查了一通MSDN,发现AcquireRequestState事件中,Session对象已经构成了,哎,都怪我当时太懒了... 那就把"授权过程"放在AcquireRequestState事件中吧. 理论上,应该会比放在授权事件中要慢一点,但是没关系,慢就慢点,总比放在页面运行环境中,来得快些,安全些:) 切入点 在IHttpModule模块的AcquireRequestState事件中做"授权过程". 效果图 开始了 步骤一(new一类库,实现IHttpModule接口) Code using System; using System.Collections.Generic; using System.Text; using System.Web; using System.Web.SessionState; using System.Web.Security; namespace HttpModule授权 { class AuthorHttpModule : System.Web.IHttpModule//, IRequiresSessionState { IHttpModule 成员#region IHttpModule 成员 public void Dispose() { } public void Init(HttpApplication context) { context.AcquireRequestState += new EventHandler(context_AcquireRequestState); } void context_AcquireRequestState(object sender, EventArgs e) { HttpApplication application = (HttpApplication)sender; // 如果用户未登录,则无需检查模块授权。 HttpRequest request = application.Request; if (!request.IsAuthenticated) return; if (application.Session["UserName"] == null) { FormsAuthentication.SignOut(); return; } // 获取用户名和Url string userName = application.Session["UserName"].ToString(); string url = application.Request.Url.ToString(); string strFileName = url.Substring(url.LastIndexOf('/')+1).Trim(); string strExeName = strFileName.Substring(strFileName.LastIndexOf('.') + 1).Trim(); // 授权过程 if (!Validator.CanUseModule(strFileName, userName)) { application.Response.Write(string.Format("sorry ,you can not acc {0} res",strFileName)); application.CompleteRequest(); } } #endregion } } 步骤二(再new一普通类,具体的授权过程看情况而定) Code using System; using System.Collections.Generic; using System.Text; namespace HttpModule授权 { public class Validator { /**//// <summary> /// 检查用户是否被授权使用模块。 /// 这里只是模拟授权,在这里用户名为wmj被授权,其他都不行 /// </summary> /// <param name="userName"></param> /// <param name="url"></param> /// <returns></returns> public static bool CanUseModule(string url,string name) { if (userName == "wmj" || url=="index.ASPx") return true; else return false; } } } 步骤三 使用方法(new一站点,在System.web节点下增加httpModules节点) Code <httpModules> <add name="HttpModuleName" type="HttpModule授权.AuthorHttpModule"/> </httpModules> 到此,配置完成 需要注意的地方 1.虽然在授权没有通过的时候,调用了application.CompleteRequest()方法,来终结http管线中的所有事件. 但是,http管线中的最后三个事件仍然会执行,并不回终结一切事件. 请想一想,如果整个http管线中的事件都不执行了,那我们怎么会看到,"没有授权的提示呢"? 2.千万不要在http管线的事件中有SQL查询语句,如果是这样,我宁愿不用这玩意(如果是这样,每次请求都要build database Connection,痛苦.) 4.站点最好设置成Form验证,(这一部分我省了) 3.虽然这是一个好想法,但是要把她实现得更加"完美",还是有一定难度的. 结尾
|
| 相关文章 |
| 发表评论 |
BK网络学院主要内容:平面设计教程,网站开发在线教程,网页制作教程,服务器教程,网络编程,数据库教程等。产业部:沪ICP备05019380号 陇ICP备05004709号 公安局:GR6201030003 Copyright © BK设计 Powered by BK网络学院 |