您的位置:首页 > 理论基础 > 计算机网络

利用HttpModule和forms身份验证,实现角色验证控制

2006-08-16 17:59 676 查看
这段时间项目进入结束阶段,一直处于空闲状态,没事就把以前收集的一些代码研究了一下,发现ASP.NET真的是很强大,光一个web.config,我要真正透彻的了解它,还要花点功夫namespace WebApplication1
/**//// <summary>
/// Summary description for AuthenticationModule.
/// </summary>
public class AuthenticationModule : IHttpModule
public AuthenticationModule()
//
// TODO: Add constructor logic here
//
}

private void Authentication_Request(object sender,EventArgs e)
HttpApplication App = (HttpApplication) sender;
HttpContext Ctx = App.Context ;
if (Ctx.Request.IsAuthenticated == true)
FormsIdentity Id = (FormsIdentity)Ctx.User.Identity ;
FormsAuthenticationTicket Ticket = Id.Ticket ;
string[] Roles = Ticket.UserData.Split (',') ;
Ctx.User = new GenericPrincipal (Id, Roles) ;
}
}

IHttpModule Members#region IHttpModule Members

void IHttpModule.Init(HttpApplication context)
context.AuthenticateRequest += new EventHandler(this.Authentication_Request);
}

void IHttpModule.Dispose()
}

#endregion
}

}
在上面的Authentication_Request方法创建一个 FormsIdentity 对象和一个 GenericPrincipal 对象。前一个对象从票名称获得用户名,后一个对象将此标识与用户角色列表包含在一起。
最后,请务必在web.config中注册你刚编写的AuthenticationModule类,位置在刚才修改身份验证方式的system.web的节点下,添加如下代码:
<httpModules>
<add name="AuthenticationModule" type="WebApplication1.AuthenticationModule, WebApplication1" />
</httpModules>
大功告成,现在可以编译通过后,将index1.aspx设置为起始页,运行一下,是不是重定向到login.aspx页面了?然后分别用user和admin登陆,看看效果。
结束语:如果不用httpModule,也可以把刚才Authenticate_Requset方法中的内容,放入global.asax.cs文件的Application_AuthenticateRequest方法中,效果也是一样的,不过这里我有一个小小的疑问,在网上查了不少文章是在global.asax.cs的Application_AuthorizeRequest方法中处理刚才的代码的,我试过不行,必须放在Application_AuthenticateRequest方法中,因为Application_AuthenticateRequest在Application_AuthorizeRequest之前运行,希望大家指点一下,到底是我弄错了还是网上写错了?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: