1. 在 Global.asax 配置
void Application_BeginRequest(object sender, EventArgs e)
{
2. 在web.config 中配置 httpModules
|
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;
/// <summary> /// SecurityHttpModule 的摘要说明 /// </summary> public class SecurityHttpModule : IHttpModule { //起用这个验证 要在WebConfig 中加上 这个 每一个 资源请求 都来认证一下
//<httpModules> // <add name="SecurityHttpModule" type="SecurityHttpModule" /> //</httpModules> public SecurityHttpModule() { // // TODO: 在此处添加构造函数逻辑 // }
#region IHttpModule 成员
//需要改进 的是 对 皮肤等 附加的 访问问题 ,这样 访问 会变慢
/// <summary>模块初始化和得到requests请求的句柄</summary> /// <param name="context" /// >An <see cref="T:System.Web.HttpApplication" /> /// 是一个权限 /// that provides access to the methods, properties, /// and events common to all application objects within /// an ASP.NET application </param> public void Init(System.Web.HttpApplication context) { context.AuthenticateRequest += new EventHandler(this.AuthenticateRequest); }
/// <summary>Occurs when a security module /// has established the identity of the user.</summary> private void AuthenticateRequest(Object sender, EventArgs e) { HttpApplication Application = (HttpApplication)sender; HttpRequest Request = Application.Context.Request; HttpResponse Response = Application.Context.Response; bool allow = false; // Default is not not allow
// Exit if we're on login.aspx, // not authenticated, or no siteMapNode exists. if (Request.Url.AbsolutePath.ToLower() == FormsAuthentication.LoginUrl.ToLower()) return; if (Application.Context.User == null) Response.Redirect(FormsAuthentication.LoginUrl); if (SiteMap.CurrentNode == null) return; //当前请求页为空时,可能是非法访问,要跳到登录窗口,并提示(未实现)
// Check if user is in roles if (SiteMap.CurrentNode.Roles.Count == 0) { allow = true; // No Roles found, so we allow. } else {
// Loop through each role and check to see if user is in it. foreach (string role in SiteMap.CurrentNode.Roles) { if (Roles.IsUserInRole(role)) { allow = true; break; } } }
// Do we deny? if (allow == false) Response.Redirect(FormsAuthentication.LoginUrl); //true 的话 请求即是通过 将继续进行,页面加载 }
/// <summary>Disposes of the resources (other than memory) /// used by the module that implements /// <see cref="T:System.Web.IHttpModule" />.</summary> public void Dispose() { }
#endregion }
|