这段时间项目进入结束阶段,一直处于空闲状态,没事就把以前收集的一些代码研究了一下,发现ASP.NET真的是很强大,光一个web.config,我要真正透彻的了解它,还要花点功夫,刚刚稍微看了一下HttpModule, 做了个小程序,写下来,当作自己的学习笔记吧。
     HttpModules实现了类似于ISAPI Filter的功能,在开发上,通常需要经过以下步骤:
    1.编写一个类,实现IhttpModule接口
    2.实现Init 方法,并且注册需要的方法 
    3.实现注册的方法
    4.实现Dispose方法,如果需要手工为类做一些清除工作,可以添加Dispose方法的实现,但这不是必需的,通常可以不为Dispose方法添加任何代码。
   5.在Web.config文件中,注册编写的类
   关于Forms身份验证,网上的说明已经很多了,下面便开始做这个小小的角色控制程序。
   首先新建asp.net项目,并添加Login.aspx, Index1.aspx,index1.aspx, default.aspx等页面。
    添加一个存储用户信息的xml文件,在里面保存用户名,密码,用户角色等信息,类似这样:
 <UsersInfo>
   <user name="admin" password="admin" role="admin" />
   <user name="user" password="user" role="user" />
</UsersInfo>
   然后在web.config文件中的system.web节点中,按照下面的代码修改authentication节点,将身份验证方式设置为forms身份验证,并将登陆页面设置为
<authentication mode="Forms">
      <forms name="TestAuth" loginUrl="Login.aspx" protection="None" timeout="60" />
  </authentication>
  另外再按如下方式增加如下节点控制用户对页面的访问的控制:
   <location path="Index1.aspx">
    <system.web>
      <authorization>
        <deny users="?" roles="user"/>
      </authorization>
    </system.web>
  </location>
   接下来在login.aspx.cs中,加上对登陆button的click事件处理函数,这里我们在IsAuthenticated方法中检查用户名密码是否通过验证,并在通过验证后取得xml文件的roles信息,然后生成FormsAuthenticationTicket,并将roles信息保存在ticket的userdata中,然后将ticket加入到客户端的cookie中,同时重定向到用户最初请求的页面。

  
private void Button1_Click(object sender, System.EventArgs e)
  {
   if(this.IsAuthenticated(TextBox1.Text,TextBox2.Text))
   {  
    string userId = TextBox1.Text;
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,userId,DateTime.Now,DateTime.Now.AddSeconds(30),false,roles);
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,FormsAuthentication.Encrypt(ticket));
    Response.Cookies.Add(cookie);
    Response.Redirect(FormsAuthentication.GetRedirectUrl(userId,false),true);
   }
  }
   然后在项目中添加新类,继承IHttpModule接口,实现Init 方法,并且注册需要的方法 :
  
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
    }

    
}
       在上面的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之前运行,希望大家指点一下,到底是我弄错了还是网上写错了?



      


posted on 2006-08-16 17:59  紫mm  阅读(1879)  评论(4编辑  收藏  举报